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,729
Warm up ImportCompletion cache in background when opening a document
Closes #37197
genlu
2021-08-19T19:35:38Z
2021-08-30T19:55:34Z
50833c98fbe69edfabced985a7895bbe9c560793
8de6661fc91b8c6c93d1c506ca573e8180bae139
Warm up ImportCompletion cache in background when opening a document. Closes #37197
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractRegionDataFlowPass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionDataFlowPass : DefiniteAssignmentPass { internal AbstractRegionDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> initiallyAssignedVariables = null, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes = null, bool trackUnassignments = false) : base(compilation, member, node, firstInRegion, lastInRegion, initiallyAssignedVariables, unassignedVariableAddressOfSyntaxes, trackUnassignments) { } /// <summary> /// To scan the whole body, we start outside (before) the region. /// </summary> protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { MakeSlots(MethodParameters); if ((object)MethodThisParameter != null) GetOrCreateSlot(MethodThisParameter); var result = base.Scan(ref badRegion); return result; } public override BoundNode VisitLambda(BoundLambda node) { MakeSlots(node.Symbol.Parameters); return base.VisitLambda(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { MakeSlots(node.Symbol.Parameters); return base.VisitLocalFunctionStatement(node); } private void MakeSlots(ImmutableArray<ParameterSymbol> parameters) { // assign slots to the parameters foreach (var parameter in parameters) { GetOrCreateSlot(parameter); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionDataFlowPass : DefiniteAssignmentPass { internal AbstractRegionDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> initiallyAssignedVariables = null, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes = null, bool trackUnassignments = false) : base(compilation, member, node, firstInRegion, lastInRegion, initiallyAssignedVariables, unassignedVariableAddressOfSyntaxes, trackUnassignments) { } /// <summary> /// To scan the whole body, we start outside (before) the region. /// </summary> protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { MakeSlots(MethodParameters); if ((object)MethodThisParameter != null) GetOrCreateSlot(MethodThisParameter); var result = base.Scan(ref badRegion); return result; } public override BoundNode VisitLambda(BoundLambda node) { MakeSlots(node.Symbol.Parameters); return base.VisitLambda(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { MakeSlots(node.Symbol.Parameters); return base.VisitLocalFunctionStatement(node); } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { return node; } private void MakeSlots(ImmutableArray<ParameterSymbol> parameters) { // assign slots to the parameters foreach (var parameter in parameters) { GetOrCreateSlot(parameter); } } } }
1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/RegionAnalysisTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; 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 { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(53591, "https://github.com/dotnet/roslyn/issues/53591")] public void TestNameOfInLambda() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { Func<string> x = /*<bind>*/() => nameof(ClosureCreated)/*</bind>*/; } }"); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); } [Fact, WorkItem(53591, "https://github.com/dotnet/roslyn/issues/53591")] public void TestNameOfWithAssignmentInLambda() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { Func<string> x = /*<bind>*/() => nameof(this = null)/*</bind>*/; } }"); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); } [Fact, WorkItem(53591, "https://github.com/dotnet/roslyn/issues/53591")] public void TestUnreachableThisInLambda() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { Func<string> x = /*<bind>*/() => false ? this.ToString() : string.Empty/*</bind>*/; } }"); Assert.True(analysis.Succeeded); Assert.Equal("this", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion } }
1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Test/Semantic/Semantics/OutVarTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using static Roslyn.Test.Utilities.TestMetadata; using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.OutVar)] public class OutVarTests : CompilingTestBase { [Fact] public void OldVersion() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")] [WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")] public void DiagnosticsDifferenceBetweenLanguageVersions_01() { var text = @" public class Cls { public static void Test1() { Test(out int x1); } public static void Test2() { var x = new Cls(out int x2); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test(out int x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22), // (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33), // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_01() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_02() { var text = @" public class Cls { public static void Main() { Test1(out (var x1, var x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_03() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, long x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,28): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_04() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, (long x2, byte x3))); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,29): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29), // (6,38): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38), // (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,29): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29), // (6,38): error CS0165: Use of unassigned local variable 'x3' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_05() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2, x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_06() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; Test1(out var (x1)); System.Console.WriteLine(F1); } static ref int var(object x) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_07() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, x2: x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2: x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_08() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (ref x1, x2)); System.Console.WriteLine(F1); } static ref int var(ref object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (ref x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_09() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, (x2))); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_10() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var ((x1), x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var ((x1), x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_11() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_12() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out M1 (x1, x2)); System.Console.WriteLine(F1); } static ref int M1(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_13() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(ref var (x1, x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(ref int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(ref var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_14() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(var (x1, x2)); System.Console.WriteLine(F1); } static int var(object x1, object x2) { F1 = 123; return 124; } static object Test1(int x) { System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"124 123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_15() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out M1 (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int M1(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_16() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (a: x2, b: x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (a: x2, b: x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } 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; } internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == name); } private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name) { return GetDeclarations(tree, name).Single(); } internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name) { return GetOutVarDeclarations(tree, name).Single(); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name); } 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 IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration()); } [Fact] public void Simple_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); int x2; Test3(out x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references); } private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references); } internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode( SemanticModel model, DeclarationExpressionSyntax decl, IdentifierNameSyntax reference) { VerifyModelForOutVar( model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: reference); } private static void VerifyModelForOutVar( SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, bool isShadowed, bool verifyDataFlow = true, LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax); Assert.NotNull(symbol); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.False(((ILocalSymbol)symbol).IsFixed); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single(); if (isShadowed) { Assert.NotEqual(symbol, other); } else { Assert.Same(symbol, other); } Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type); 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, model.GetTypeInfo(reference).Type); } if (verifyDataFlow) { VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol); } } private static void AssertInfoForDeclarationExpressionSyntax( SemanticModel model, DeclarationExpressionSyntax decl, ISymbol expectedSymbol = null, ITypeSymbol expectedType = null ) { var symbolInfo = model.GetSymbolInfo(decl); Assert.Equal(expectedSymbol, symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl)); var typeInfo = model.GetTypeInfo(decl); Assert.Equal(expectedType, typeInfo.Type); // skip cases where operation is not supported AssertTypeFromOperation(model, expectedType, decl); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.Equal(expectedType, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl)); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.True(model.GetConversion(decl).IsIdentity); var typeSyntax = decl.Type; Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax)); Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax)); ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType(); if (expected?.IsErrorType() != false) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol); } typeInfo = model.GetTypeInfo(typeSyntax); Assert.Equal(expected, typeInfo.Type); Assert.Equal(expected, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax)); Assert.True(model.GetConversion(typeSyntax).IsIdentity); var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false); Assert.False(conversion.Exists); Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Null(model.GetDeclaredSymbol(decl)); } private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl) { // see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail // unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode. // what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from // error recovery mode var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault(); if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true) { // invalid syntax case where operation is not supported return; } Assert.Equal(expectedType, model.GetOperation(decl)?.Type); } private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol) { var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax; if (dataFlowParent == null) { if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax)) { Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent); } return; } if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); return; } var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (isExecutableCode) { Assert.True(dataFlow.Succeeded); Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); if (!isDelegateCreation) { Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); var flowsIn = FlowsIn(dataFlowParent, decl, references); Assert.Equal(flowsIn, dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(flowsIn, dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(FlowsOut(dataFlowParent, decl, references), dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(ReadOutside(dataFlowParent, references), dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(WrittenOutside(dataFlowParent, references), dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type); } private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; Assert.NotEqual(SymbolKind.Field, symbol.Kind); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; if (symbol.Kind == SymbolKind.Local) { var local = symbol.GetSymbol<SourceLocalSymbol>(); var parent = local.IdentifierToken.Parent; Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration())); if (parent.Kind() == SyntaxKind.VariableDeclarator) { var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent; switch (parent1.Kind()) { case SyntaxKind.FixedStatement: case SyntaxKind.ForStatement: case SyntaxKind.UsingStatement: break; default: Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind()); break; } } } Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl) { return (SingleVariableDesignationSyntax)decl.Designation; } private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart) { if (IsRead(reference)) { return true; } } } return false; } private static bool IsRead(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left != reference) { return true; } break; default: return true; } return false; } private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsRead(reference)) { return true; } } } return false; } private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { ForStatementSyntax forStatement; if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null && forStatement.Incrementors.Span.Contains(decl.Position) && forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null)) { return false; } var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault(); var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax); MethodDeclarationSyntax methodDeclParent; if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" && ((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null || methodDeclParent.Body.Statements.First() != containingReturnOrThrow)) { return false; } foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span) && (containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) && (reference.SpanStart > decl.SpanStart || (containingReturnOrThrow == null && reference.Ancestors().OfType<DoStatementSyntax>().Join( decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any()))) { if (IsRead(reference)) { return true; } } } return false; } private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsWrite(reference)) { return true; } } } return false; } private static bool IsWrite(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left == reference) { return true; } break; case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.PostDecrementExpression: return true; default: return false; } return false; } [Fact] public void Simple_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Int32 x1), x1); int x2 = 0; Test3(x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_03() { var text = @" public class Cls { public static void Main() { Test2(Test1(out (int, int) x1), x1); } static object Test1(out (int, int) x) { x = (123, 124); return null; } static void Test2(object x, (int, int) y) { System.Console.WriteLine(y); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_04() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1); } static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = new System.Collections.Generic.List<System.Int32>(); return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, out x1), x1); } static object Test1(out int x, out int y) { x = 123; y = 124; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, x1 = 124), x1); } static object Test1(out int x, int y) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_07() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1, x1 = 124); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y, int z) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_08() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), ref x1); int x2 = 0; Test3(ref x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, ref int y) { System.Console.WriteLine(y); } static void Test3(ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_09() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), out x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_10() { var text = @" public class Cls { public static void Main() { Test2(Test1(out dynamic x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_11() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int[] x1), x1); } static object Test1(out int[] x) { x = new [] {123}; return null; } static void Test2(object x, int[] y) { System.Console.WriteLine(y[0]); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_01() { var text = @" public class Cls { public static void Main() { int x1 = 0; Test1(out int x1); Test2(Test1(out int x2), out int x2); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS0128: A local variable named 'x1' is already defined in this scope // Test1(out int x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23), // (9,29): error CS0128: A local variable named 'x2' is already defined in this scope // out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13) ); } [Fact] public void Scope_02() { var text = @" public class Cls { public static void Main() { Test2(x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15) ); } [Fact] public void Scope_03() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_04() { var text = @" public class Cls { public static void Main() { Test1(out int x1); System.Console.WriteLine(x1); } static object Test1(out int x) { x = 1; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_05() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out var x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_Attribute_01() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_02() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_03() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_04() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void AttributeArgument_01() { var source = @" public class X { [Test(out var x3)] [Test(out int x4)] [Test(p: out var x5)] [Test(p: out int x6)] public static void Main() { } } class Test : System.Attribute { public Test(out int p) { p = 100; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (4,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out var x3)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11), // (4,19): error CS1003: Syntax error, ',' expected // [Test(out var x3)] Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19), // (5,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out int x4)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11), // (5,15): error CS1525: Invalid expression term 'int' // [Test(out int x4)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15), // (5,19): error CS1003: Syntax error, ',' expected // [Test(out int x4)] Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19), // (6,14): error CS1525: Invalid expression term 'out' // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14), // (6,14): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18), // (6,22): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22), // (7,14): error CS1525: Invalid expression term 'out' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14), // (7,14): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14), // (7,18): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18), // (7,18): error CS1525: Invalid expression term 'int' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22), // (4,15): error CS0103: The name 'var' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15), // (4,19): error CS0103: The name 'x3' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19), // (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out var x3)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6), // (5,19): error CS0103: The name 'x4' does not exist in the current context // [Test(out int x4)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19), // (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out int x4)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6), // (6,18): error CS0103: The name 'var' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18), // (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18), // (6,22): error CS0103: The name 'x5' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22), // (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6), // (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18), // (7,22): error CS0103: The name 'x6' does not exist in the current context // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22), // (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6) ); var tree = compilation.SyntaxTrees.Single(); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); Assert.False(GetOutVarDeclarations(tree, "x4").Any()); Assert.False(GetOutVarDeclarations(tree, "x5").Any()); Assert.False(GetOutVarDeclarations(tree, "x6").Any()); } [Fact] public void Scope_Catch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } } void Test4() { var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Scope_Catch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out int x1) && x1 > 0) { Dummy(x1); } } void Test4() { int x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out int x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out int x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out int x7) && x7 > 0) { int x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out int x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out int x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out int x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out int x10)) { int y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out int x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out int x14), TakeOutParam(out int x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out int x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out int x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out int x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out int x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out int x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Catch_01_ExplicitType() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Scope_ConstructorInitializers_01() { var source = @" public class X { public static void Main() { } X(byte x) : this(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : this(x4 && TakeOutParam(4, out int x4)) {} X(short x) : this(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : this(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : this(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : this(x7, 2) {} void Test73() { Dummy(x7, 3); } X(params object[] x) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : this(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : this(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_02() { var source = @" public class X : Y { public static void Main() { } X(byte x) : base(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : base(x4 && TakeOutParam(4, out int x4)) {} X(short x) : base(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : base(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : base(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : base(x7, 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } public class Y { public Y(params object[] x) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : base(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : base(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_03() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D { public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_04() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D : C { public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_05() { var source = @"using System; class D { public D(int o) : this(SpeculateHere) { } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_06() { var source = @"using System; class D : C { public D(int o) : base(SpeculateHere) { } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var initializerOperation = model.GetOperation(initializer); Assert.Null(initializerOperation.Parent.Parent.Parent); VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Expression: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)') Children(1): IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5') IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5') Left: IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o') IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5') Left: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] public void Scope_ConstructorInitializers_07() { var source = @" public class X : Y { public static void Main() { } X(byte x3) : base(TakeOutParam(3, out var x3)) {} X(sbyte x) : base(TakeOutParam(4, out var x4)) { int x4 = 1; System.Console.WriteLine(x4); } X(ushort x) : base(TakeOutParam(51, out var x5)) => Dummy(TakeOutParam(52, out var x5), x5); X(short x) : base(out int x6, x6) {} X(uint x) : base(out var x7, x7) {} X(int x) : base(TakeOutParam(out int x8, x8)) {} X(ulong x) : base(TakeOutParam(out var x9, x9)) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } public class Y { public Y(params object[] x) {} public Y(out int x, int y) { x = y; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : base(TakeOutParam(3, out var x3)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40), // (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x4 = 1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13), // (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // => Dummy(TakeOutParam(52, out var x5), x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39), // (24,28): error CS0165: Use of unassigned local variable 'x6' // : base(out int x6, x6) Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28), // (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list. // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28), // (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20), // (32,41): error CS0165: Use of unassigned local variable 'x8' // : base(TakeOutParam(out int x8, x8)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41), // (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list. // : base(TakeOutParam(out var x9, x9)) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").Single(); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref); } [Fact] public void Scope_Do_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { do { Dummy(x1); } while (TakeOutParam(true, out var x1) && x1); } void Test2() { do Dummy(x2); while (TakeOutParam(true, out var x2) && x2); } void Test4() { var x4 = 11; Dummy(x4); do Dummy(x4); while (TakeOutParam(true, out var x4) && x4); } void Test6() { do Dummy(x6); while (x6 && TakeOutParam(true, out var x6)); } void Test7() { do { var x7 = 12; Dummy(x7); } while (TakeOutParam(true, out var x7) && x7); } void Test8() { do Dummy(x8); while (TakeOutParam(true, out var x8) && x8); System.Console.WriteLine(x8); } void Test9() { do { Dummy(x9); do Dummy(x9); while (TakeOutParam(true, out var x9) && x9); // 2 } while (TakeOutParam(true, out var x9) && x9); } void Test10() { do { var y10 = 12; Dummy(y10); } while (TakeOutParam(y10, out var x10)); } //void Test11() //{ // do // { // let y11 = 12; // Dummy(y11); // } // while (TakeOutParam(y11, out var x11)); //} void Test12() { do var y12 = 12; while (TakeOutParam(y12, out var x12)); } //void Test13() //{ // do // let y13 = 12; // while (TakeOutParam(y13, out var x13)); //} void Test14() { do { Dummy(x14); } while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13), // (14,19): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19), // (22,19): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19), // (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43), // (32,19): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy(x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19), // (40,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16), // (39,19): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19), // (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17), // (56,19): error CS0841: Cannot use local variable 'x8' before it is declared // Dummy(x8); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19), // (59,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34), // (66,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19), // (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9); // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47), // (68,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23), // (81,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29), // (98,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29), // (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17), // (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46), // (112,19): error CS0841: Cannot use local variable 'x14' before it is declared // Dummy(x14); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[1]); VerifyNotAnOutLocal(model, x7Ref[0]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[1]); VerifyNotAnOutLocal(model, y10Ref[0]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Do_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) do { } while (TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Do_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@" do {} while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { int f = 1; do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false); if (f) { do ; while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { } bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0; bool Test4(object o) => x4 && TakeOutParam(o, out int x4); bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0; void Test72() => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test11(object x11) => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,29): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4(object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29), // (13,67): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67), // (19,28): error CS0103: The name 'x7' does not exist in the current context // void Test72() => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool Test11(object x11) => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")] public void Scope_ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test3() { bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0; f(null); } void Test4() { bool f (object o) => x4 && TakeOutParam(o, out int x4); f(null); } void Test5() { bool f (object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; f(null, null); } void Test6() { bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0; f1(null); f2(null); } void Test7() { Dummy(x7, 1); bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0; Dummy(x7, 2); f(null); } void Test11() { var x11 = 11; Dummy(x11); bool f (object o) => TakeOutParam(o, out int x11) && x11 > 0; f(null); } void Test12() { bool f (object o) => TakeOutParam(o, out int x12) && x12 > 0; var x12 = 11; Dummy(x12); f(null); } System.Action Test13() { return () => { bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0; f(null); }; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15), // (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54), // (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); // Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214 var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").Single(); VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref); } [Fact] public void ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out int x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedLocalFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out var x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void Scope_ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { } bool Test3 => TakeOutParam(3, out int x3) && x3 > 0; bool Test4 => x4 && TakeOutParam(4, out int x4); bool Test5 => TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0; bool Test71 => TakeOutParam(7, out int x7) && x7 > 0; bool Test72 => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool this[object x11] => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,19): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 => x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19), // (13,44): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44), // (19,26): error CS0103: The name 'x7' does not exist in the current context // bool Test72 => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool this[object x11] => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void ExpressionBodiedProperties_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void Scope_ExpressionStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { Dummy(TakeOutParam(true, out var x1), x1); { Dummy(TakeOutParam(true, out var x1), x1); } Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ExpressionStatement_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) Test2(Test1(out int x1), x1); if (test) { Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_ExpressionStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ExpressionStatement_04() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Scope_FieldInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 = x4 && TakeOutParam(4, out int x4); bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,57): error CS0103: The name 'x8' does not exist in the current context // bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57), // (23,19): error CS0103: The name 'x9' does not exist in the current context // bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReference(tree, "x8"); VerifyModelForOutVar(model, x8Decl); VerifyNotInScope(model, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReference(tree, "x9"); VerifyNotInScope(model, x9Ref); VerifyModelForOutVar(model, x9Decl); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_FieldInitializers_02() { var source = @"using static Test; public enum X { Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0, Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Test72 = x7, } class Test { public static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'x4' before it is declared // Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13), // (9,38): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38), // (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant // Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13), // (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14), // (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70), // (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant // Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14), // (15,14): error CS0103: The name 'x7' does not exist in the current context // Test72 = x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14), // (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant // Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0') Locals: Local_1: System.Int32 x3 IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0') Condition: IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_FieldInitializers_03() { var source = @" public class X { public static void Main() { } const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; const bool Test4 = x4 && TakeOutParam(4, out int x4); const bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; const bool Test72 = x7 > 2; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant // const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24), // (10,24): error CS0841: Cannot use local variable 'x4' before it is declared // const bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24), // (13,49): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49), // (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant // const bool Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("X.Test5").WithLocation(12, 24), // (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25), // (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73), // (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant // const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25), // (19,25): error CS0103: The name 'x7' does not exist in the current context // const bool Test72 = x7 > 2; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_FieldInitializers_04() { var source = @" class X : Y { public static void Main() { } bool Test3 = TakeOutParam(out int x3, x3); bool Test4 = TakeOutParam(out var x4, x4); bool Test5 = TakeOutParam(out int x5, 5); X() : this(x5) { System.Console.WriteLine(x5); } X(object x) : base(x5) => System.Console.WriteLine(x5); static bool Test6 = TakeOutParam(out int x6, 6); static X() { System.Console.WriteLine(x6); } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } class Y { public Y(object y) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,43): error CS0165: Use of unassigned local variable 'x3' // bool Test3 = TakeOutParam(out int x3, x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43), // (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list. // bool Test4 = TakeOutParam(out var x4, x4); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43), // (15,12): error CS0103: The name 'x5' does not exist in the current context // : this(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12), // (17,34): error CS0103: The name 'x5' does not exist in the current context // System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34), // (21,12): error CS0103: The name 'x5' does not exist in the current context // : base(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12), // (22,33): error CS0103: The name 'x5' does not exist in the current context // => System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33), // (27,34): error CS0103: The name 'x6' does not exist in the current context // System.Console.WriteLine(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(4, x5Ref.Length); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); VerifyNotInScope(model, x5Ref[3]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void FieldInitializers_05() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,54): error CS0165: Use of unassigned local variable 'x1' // bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void FieldInitializers_06() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void Scope_Fixed_01() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p = Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // fixed (int* p = Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { fixed (int* p = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Fixed_02() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* x1 = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2), x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p = Dummy(TakeOutParam(true, out var x3) && x3)) { Dummy(x3); } } void Test4() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4), p2 = Dummy(TakeOutParam(true, out var x4) && x4)) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (14,66): error CS0165: Use of unassigned local variable 'x1' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2 = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Fixed_02() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Scope_For_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for ( Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (; Dummy(TakeOutParam(true, out var x1) && x1) ;) { Dummy(x1); } } void Test2() { for (; Dummy(TakeOutParam(true, out var x2) && x2) ;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (; Dummy(TakeOutParam(true, out var x4) && x4) ;) Dummy(x4); } void Test6() { for (; Dummy(x6 && TakeOutParam(true, out var x6)) ;) Dummy(x6); } void Test7() { for (; Dummy(TakeOutParam(true, out var x7) && x7) ;) { var x7 = 12; Dummy(x7); } } void Test8() { for (; Dummy(TakeOutParam(true, out var x8) && x8) ;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (; Dummy(TakeOutParam(true, out var x9) && x9) ;) { Dummy(x9); for (; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;) Dummy(x9); } } void Test10() { for (; Dummy(TakeOutParam(y10, out var x10)) ;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (; // Dummy(TakeOutParam(y11, out var x11)) // ;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (; Dummy(TakeOutParam(y12, out var x12)) ;) var y12 = 12; } //void Test13() //{ // for (; // Dummy(TakeOutParam(y13, out var x13)) // ;) // let y13 = 12; //} void Test14() { for (; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_03() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(TakeOutParam(true, out var x1) && x1) ) { Dummy(x1); } } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2) ) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (;; Dummy(TakeOutParam(true, out var x4) && x4) ) Dummy(x4); } void Test6() { for (;; Dummy(x6 && TakeOutParam(true, out var x6)) ) Dummy(x6); } void Test7() { for (;; Dummy(TakeOutParam(true, out var x7) && x7) ) { var x7 = 12; Dummy(x7); } } void Test8() { for (;; Dummy(TakeOutParam(true, out var x8) && x8) ) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (;; Dummy(TakeOutParam(true, out var x9) && x9) ) { Dummy(x9); for (;; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ) Dummy(x9); } } void Test10() { for (;; Dummy(TakeOutParam(y10, out var x10)) ) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (;; // Dummy(TakeOutParam(y11, out var x11)) // ) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (;; Dummy(TakeOutParam(y12, out var x12)) ) var y12 = 12; } //void Test13() //{ // for (;; // Dummy(TakeOutParam(y13, out var x13)) // ) // let y13 = 12; //} void Test14() { for (;; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (16,19): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19), // (25,19): error CS0103: The name 'x2' does not exist in the current context // Dummy(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (44,19): error CS0103: The name 'x6' does not exist in the current context // Dummy(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19), // (63,19): error CS0103: The name 'x8' does not exist in the current context // Dummy(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (74,19): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19), // (78,23): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23), // (71,14): warning CS0162: Unreachable code detected // Dummy(TakeOutParam(true, out var x9) && x9) Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44), // (128,19): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref[0]); VerifyNotInScope(model, x2Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref[0]); VerifyNotInScope(model, x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0]); VerifyNotInScope(model, x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyNotInScope(model, x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyNotInScope(model, x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); VerifyNotInScope(model, x14Ref[1]); } [Fact] public void Scope_For_04() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (var b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (var b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (var b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (var b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (var b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (var b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (var b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (var b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (var b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (var b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (var b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (var b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_05() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (bool b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (bool b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (bool b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (bool b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (bool b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (bool b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (bool b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_06() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var x1 = Dummy(TakeOutParam(true, out var x1) && x1) ;;) {} } void Test2() { for (var x2 = true; Dummy(TakeOutParam(true, out var x2) && x2) ;) {} } void Test3() { for (var x3 = true;; Dummy(TakeOutParam(true, out var x3) && x3) ) {} } void Test4() { for (bool x4 = Dummy(TakeOutParam(true, out var x4) && x4) ;;) {} } void Test5() { for (bool x5 = true; Dummy(TakeOutParam(true, out var x5) && x5) ;) {} } void Test6() { for (bool x6 = true;; Dummy(TakeOutParam(true, out var x6) && x6) ) {} } void Test7() { for (bool x7 = true, b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) {} } void Test8() { for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8), b2 = Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2 = Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } void Test10() { for (var b = x10; Dummy(TakeOutParam(true, out var x10) && x10) && Dummy(TakeOutParam(true, out var x10) && x10); Dummy(TakeOutParam(true, out var x10) && x10)) {} } void Test11() { for (bool b = x11; Dummy(TakeOutParam(true, out var x11) && x11) && Dummy(TakeOutParam(true, out var x11) && x11); Dummy(TakeOutParam(true, out var x11) && x11)) {} } void Test12() { for (Dummy(x12); Dummy(x12) && Dummy(TakeOutParam(true, out var x12) && x12); Dummy(TakeOutParam(true, out var x12) && x12)) {} } void Test13() { for (var b = x13; Dummy(x13); Dummy(TakeOutParam(true, out var x13) && x13), Dummy(TakeOutParam(true, out var x13) && x13)) {} } void Test14() { for (bool b = x14; Dummy(x14); Dummy(TakeOutParam(true, out var x14) && x14), Dummy(TakeOutParam(true, out var x14) && x14)) {} } void Test15() { for (Dummy(x15); Dummy(x15); Dummy(x15), Dummy(TakeOutParam(true, out var x15) && x15)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47), // (13,54): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54), // (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x2) && x2) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47), // (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used // for (var x2 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3) && x3) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used // for (var x3 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18), // (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47), // (37,54): error CS0165: Use of unassigned local variable 'x4' // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54), // (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x5) && x5) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47), // (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used // for (bool x5 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19), // (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x6) && x6) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47), // (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used // for (bool x6 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19), // (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47), // (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2 = Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52), // (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47), // (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47), // (77,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23), // (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47), // (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47), // (86,22): error CS0103: The name 'x10' does not exist in the current context // for (var b = x10; Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22), // (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope // Dummy(TakeOutParam(true, out var x10) && x10); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47), // (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x10) && x10)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47), // (95,23): error CS0103: The name 'x11' does not exist in the current context // for (bool b = x11; Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23), // (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope // Dummy(TakeOutParam(true, out var x11) && x11); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47), // (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x11) && x11)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47), // (104,20): error CS0103: The name 'x12' does not exist in the current context // for (Dummy(x12); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20), // (105,20): error CS0841: Cannot use local variable 'x12' before it is declared // Dummy(x12) && Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20), // (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x12) && x12)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47), // (113,22): error CS0103: The name 'x13' does not exist in the current context // for (var b = x13; Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22), // (114,20): error CS0103: The name 'x13' does not exist in the current context // Dummy(x13); Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20), // (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope // Dummy(TakeOutParam(true, out var x13) && x13)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47), // (122,23): error CS0103: The name 'x14' does not exist in the current context // for (bool b = x14; Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23), // (123,20): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20), // (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope // Dummy(TakeOutParam(true, out var x14) && x14)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47), // (131,20): error CS0103: The name 'x15' does not exist in the current context // for (Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20), // (132,20): error CS0103: The name 'x15' does not exist in the current context // Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20), // (133,20): error CS0841: Cannot use local variable 'x15' before it is declared // Dummy(x15), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(3, x10Decl.Length); Assert.Equal(4, x10Ref.Length); VerifyNotInScope(model, x10Ref[0]); VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]); VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]); var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Decl.Length); Assert.Equal(4, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]); VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]); var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Decl.Length); Assert.Equal(4, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]); VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(4, x13Ref.Length); VerifyNotInScope(model, x13Ref[0]); VerifyNotInScope(model, x13Ref[1]); VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyNotInScope(model, x14Ref[0]); VerifyNotInScope(model, x14Ref[1]); VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(4, x15Ref.Length); VerifyNotInScope(model, x15Ref[0]); VerifyNotInScope(model, x15Ref[1]); VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]); } [Fact] public void Scope_For_07() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(x1), Dummy(TakeOutParam(true, out var x1) && x1)) {} } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2), Dummy(TakeOutParam(true, out var x2) && x2)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,20): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20), // (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2) && x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_06() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1))) { x0++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"20 30 -- 20 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_07() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 -- 10 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Foreach_01() { var source = @" public class X { public static void Main() { } System.Collections.IEnumerable Dummy(params object[] x) {return null;} void Test1() { foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } void Test15() { foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60), // (35,33): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65), // (68,46): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46), // (86,46): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,57): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57), // (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_If_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (TakeOutParam(true, out var x1)) { Dummy(x1); } else { System.Console.WriteLine(x1); } } void Test2() { if (TakeOutParam(true, out var x2)) Dummy(x2); else System.Console.WriteLine(x2); } void Test3() { if (TakeOutParam(true, out var x3)) Dummy(x3); else { var x3 = 12; System.Console.WriteLine(x3); } } void Test4() { var x4 = 11; Dummy(x4); if (TakeOutParam(true, out var x4)) Dummy(x4); } void Test5(int x5) { if (TakeOutParam(true, out var x5)) Dummy(x5); } void Test6() { if (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { if (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { if (TakeOutParam(true, out var x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { if (TakeOutParam(true, out var x9)) { Dummy(x9); if (TakeOutParam(true, out var x9)) // 2 Dummy(x9); } } void Test10() { if (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } void Test12() { if (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // if (TakeOutParam(y13, out var x13)) // let y13 = 12; //} static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13), // (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x3 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17), // (46,40): error CS0128: A local variable named 'x4' is already defined in this scope // if (TakeOutParam(true, out var x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40), // (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x5)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40), // (58,13): error CS0841: Cannot use local variable 'x6' before it is declared // if (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13), // (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17), // (83,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19), // (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44), // (91,26): error CS0103: The name 'y10' does not exist in the current context // if (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26), // (100,26): error CS0103: The name 'y12' does not exist in the current context // if (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26), // (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); } [Fact] public void Scope_If_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) if (TakeOutParam(true, out var x1)) { } else { } x1++; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_If_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@" if (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, TakeOutParam(val, out var x1), x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) ; if (f) { if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_Lambda_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} System.Action<object> Test1() { return (o) => let x1 = o; } System.Action<object> Test2() { return (o) => let var x2 = o; } void Test3() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0)); } void Test4() { Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); } void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0)); } void Test6() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0)); } void Test7() { Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0), x7); Dummy(x7, 2); } void Test8() { Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8)); } void Test9() { Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && x9 > 0), x9); } void Test10() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && x10 > 0), TakeOutParam(true, out var x10), x10); } void Test11() { var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && x11 > 0), x11); } void Test12() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73), // (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73), // (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73), // (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { var d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { var d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // var d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // var d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); object d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { object d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { object d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { object d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,53): error CS0128: A local variable named 'x4' is already defined in this scope // object d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53), // (24,26): error CS0841: Cannot use local variable 'x6' before it is declared // object d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26), // (36,50): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var x1 = Dummy(TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { object x2 = Dummy(TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] public void Scope_LocalDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Scope_LocalDeclarationStmt_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y1 = Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] public void Scope_LocalDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d =TakeOutParam(true, out var x1) && x1 != null; x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (d, dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var (d, dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { var (d, dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var (d, dd, ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,51): error CS0128: A local variable named 'x4' is already defined in this scope // var (d, dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51), // (24,24): error CS0841: Cannot use local variable 'x6' before it is declared // var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); (object d, object dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { (object d, object dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { (object d, object dd, object ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,61): error CS0128: A local variable named 'x4' is already defined in this scope // (object d, object dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61), // (24,34): error CS0841: Cannot use local variable 'x6' before it is declared // (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (x1, dd) = (TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { (object x2, object dd) = (TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Dummy(x1)); Dummy(x1); } void Test2() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2), Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3), Dummy(x3)); } void Test4() { (object d1, object d2) = (Dummy(x4), Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,67): error CS0128: A local variable named 'x1' is already defined in this scope // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67), // (12,72): error CS0165: Use of unassigned local variable 'x1' // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,41): error CS0841: Cannot use local variable 'x4' before it is declared // (object d1, object d2) = (Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyNotAnOutLocal(model, x1Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_05() { var source = @" public class X { public static void Main() { } void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" var (y1, dd) = (TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var (d, dd) = (TakeOutParam(true, out var x1), x1); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] public void Scope_Lock_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { lock (Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { lock (Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Dummy(x4); } void Test6() { lock (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { lock (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { lock (Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { lock (Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { lock (Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // lock (Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { lock (Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // lock (Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { lock (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,48): error CS0128: A local variable named 'x4' is already defined in this scope // lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48), // (35,21): error CS0841: Cannot use local variable 'x6' before it is declared // lock (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (60,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19), // (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52), // (68,34): error CS0103: The name 'y10' does not exist in the current context // lock (Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34), // (86,34): error CS0103: The name 'y12' does not exist in the current context // lock (Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,45): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Lock_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { if (true) lock (Dummy(TakeOutParam(true, out var x1))) { } x1++; } static object TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (17,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Lock_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@" lock (Dummy(TakeOutParam(true, out var x1), x1)) ; "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(TakeOutParam(""lock"", out var x1), x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_ParameterDefault_01() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out int x4)) {} void Test5(bool p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0') Locals: Local_1: System.Int32 x3 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0') Left: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_ParameterDefault_02() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out var x4)) {} void Test5(bool p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out var x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_PropertyInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); bool Test5 {get;} = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 {get;} = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,25): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,32): error CS0103: The name 'x7' does not exist in the current context // bool Test72 {get;} = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_03() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,63): error CS0165: Use of unassigned local variable 'x1' // bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void PropertyInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(new X().Test1); } int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Scope_Query_01() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); } void Test2() { var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); } void Test3() { var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); } void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } void Test6() { var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); } void Test7() { var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); } void Test8() { var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); } void Test9() { var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); } void Test10() { var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; } void Test11() { var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,26): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26), // (27,15): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15), // (35,32): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32), // (37,15): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15), // (45,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35), // (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35), // (49,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32), // (49,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36), // (52,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15), // (53,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15), // (61,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35), // (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35), // (66,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32), // (66,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36), // (69,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15), // (70,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15), // (78,26): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26), // (80,15): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15), // (87,27): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27), // (89,27): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27), // (91,26): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26), // (91,31): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31), // (93,15): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15), // (94,15): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15), // (102,15): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15), // (112,25): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25), // (109,25): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25), // (114,15): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15), // (115,15): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15), // (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24), // (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } [Fact] public void Scope_Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35), // (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35), // (22,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32), // (22,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36), // (25,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15), // (26,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15), // (35,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35), // (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35), // (40,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32), // (40,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36), // (43,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15), // (44,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0; var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0); Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62), // (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51), // (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58), // (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49), // (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51), // (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51), // (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47), // (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49), // (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54), // (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(3, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVarDuplicateInSameScope(model, yDecl); VerifyNotAnOutLocal(model, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); break; } VerifyNotAnOutLocal(model, yRef[2]); switch (i) { case 12: VerifyNotAnOutLocal(model, yRef[1]); break; default: VerifyNotAnOutLocal(model, yRef[1]); break; } } var y13Decl = GetOutVarDeclarations(tree, "y13").Single(); var y13Ref = GetReference(tree, "y13"); VerifyModelForOutVar(model, y13Decl, y13Ref); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_06() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y1), TakeOutParam(out int y2), TakeOutParam(out int y3), TakeOutParam(out int y4), TakeOutParam(out int y5), TakeOutParam(out int y6), TakeOutParam(out int y7), TakeOutParam(out int y8), TakeOutParam(out int y9), TakeOutParam(out int y10), TakeOutParam(out int y11), TakeOutParam(out int y12), from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62), // (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51), // (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58), // (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49), // (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51), // (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51), // (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47), // (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49), // (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54), // (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); break; case 12: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; default: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; } } } [Fact] public void Scope_Query_07() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y3), from x1 in new[] { 0 } select x1 into x1 join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on x1 equals x3 select y3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,62): error CS0128: A local variable named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); const string id = "y3"; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); // Since the name is declared twice in the same scope, // both references are to the same declaration. VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); } [Fact] public void Scope_Query_08() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4) ) ? 1 : 0} from y1 in new[] { 1 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by x1 into y4 select y4; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // from y1 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24), // (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24), // (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23), // (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 5; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_09() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by 1 into y4 select y4 == null ? 1 : 0 into x2 join y5 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4), TakeOutParam(out var y5) ) ? 1 : 0 } on x2 equals y5 select x2; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // var res = from y1 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24), // (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24), // (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23), // (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24), // (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5' // join y5 in new[] { Dummy(TakeOutParam(out var y1), Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 6; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); switch (i) { case 4: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; case 5: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; default: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; } } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] [WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")] public void Scope_Query_10() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } select y1; } void Test2() { var res = from y2 in new[] { 0 } join x3 in new[] { 1 } on TakeOutParam(out var y2) ? y2 : 0 equals x3 select y2; } void Test3() { var res = from x3 in new[] { 0 } join y3 in new[] { 1 } on x3 equals TakeOutParam(out var y3) ? y3 : 0 select y3; } void Test4() { var res = from y4 in new[] { 0 } where TakeOutParam(out var y4) && y4 == 1 select y4; } void Test5() { var res = from y5 in new[] { 0 } orderby TakeOutParam(out var y5) && y5 > 1, 1 select y5; } void Test6() { var res = from y6 in new[] { 0 } orderby 1, TakeOutParam(out var y6) && y6 > 1 select y6; } void Test7() { var res = from y7 in new[] { 0 } group TakeOutParam(out var y7) && y7 == 3 by y7; } void Test8() { var res = from y8 in new[] { 0 } group y8 by TakeOutParam(out var y8) && y8 == 3; } void Test9() { var res = from y9 in new[] { 0 } let x4 = TakeOutParam(out var y9) && y9 > 0 select y9; } void Test10() { var res = from y10 in new[] { 0 } select TakeOutParam(out var y10) && y10 > 0; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052 compilation.VerifyDiagnostics( // (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59), // (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(out var y2) ? y2 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48), // (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(out var y3) ? y3 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52), // (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(out var y4) && y4 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46), // (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(out var y5) && y5 > 1, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48), // (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(out var y6) && y6 > 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48), // (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(out var y7) && y7 == 3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46), // (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(out var y8) && y8 == 3; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43), // (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x4 = TakeOutParam(out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49), // (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(out var y10) && y10 > 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 11; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(i == 10 ? 1 : 2, yRef.Length); switch (i) { case 4: case 6: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; case 8: VerifyModelForOutVar(model, yDecl, yRef[1]); VerifyNotAnOutLocal(model, yRef[0]); break; case 10: VerifyModelForOutVar(model, yDecl, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; } } } [Fact] public void Scope_Query_11() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y1), from x2 in new [] { y1 } where TakeOutParam(x1, out var y1) select x2) select x1; } void Test2() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y2), TakeOutParam(x1 + 1, out var y2)) select x1; } void Test3() { var res = from x1 in new [] { 1 } where TakeOutParam(out int y3, y3) select x1; } void Test4() { var res = from x1 in new [] { 1 } where TakeOutParam(out var y4, y4) select x1; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x, int y) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(x1, out var y1) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62), // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray(); var y1Ref = GetReferences(tree, "y1").Single(); Assert.Equal(2, y1Decl.Length); VerifyModelForOutVar(model, y1Decl[0], y1Ref); VerifyModelForOutVar(model, y1Decl[1]); var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray(); Assert.Equal(2, y2Decl.Length); VerifyModelForOutVar(model, y2Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").Single(); VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").Single(); VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0} join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0} on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0 equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0 where TakeOutParam(6, out var y6) && Print(y6) orderby TakeOutParam(7, out var y7) && Print(y7), TakeOutParam(8, out var y8) && Print(y8) group TakeOutParam(9, out var y9) && Print(y9) by TakeOutParam(10, out var y10) && Print(y10) into g let x11 = TakeOutParam(11, out var y11) && Print(y11) select TakeOutParam(12, out var y12) && Print(y12); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl, yRef); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString()); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutVar(model, yDecl, yRef); } [Fact] public void Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in new[] { true } select a && TakeOutParam(3, out int x1) || x1 > 0; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,62): error CS0165: Use of unassigned local variable 'x1' // select a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); compilation.VerifyOperationTree(x1Decl, expectedOperationTree: @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') "); } [Fact] public void Query_04() { var source = @" using System.Linq; public class X { public static void Main() { System.Console.WriteLine(Test1()); } static int Test1() { var res = from a in new[] { 1 } select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; return res.Single(); } static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in (new[] { 1 }).AsQueryable() select TakeOutParam(a, out int x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,46): error CS8198: An expression tree may not contain an out argument variable declaration. // select TakeOutParam(a, out int x1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46) ); } [Fact] public void Scope_ReturnStatement_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) { return null; } object Test1() { return Dummy(TakeOutParam(true, out var x1), x1); { return Dummy(TakeOutParam(true, out var x1), x1); } return Dummy(TakeOutParam(true, out var x1), x1); } object Test2() { return Dummy(x2, TakeOutParam(true, out var x2)); } object Test3(int x3) { return Dummy(TakeOutParam(true, out var x3), x3); } object Test4() { var x4 = 11; Dummy(x4); return Dummy(TakeOutParam(true, out var x4), x4); } object Test5() { return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //object Test6() //{ // let x6 = 11; // Dummy(x6); // return Dummy(TakeOutParam(true, out var x6), x6); //} //object Test7() //{ // return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} object Test8() { return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } object Test9(bool y9) { if (y9) return Dummy(TakeOutParam(true, out var x9), x9); return null; } System.Func<object> Test10(bool y10) { return () => { if (y10) return Dummy(TakeOutParam(true, out var x10), x10); return null;}; } object Test11() { Dummy(x11); return Dummy(TakeOutParam(true, out var x11), x11); } object Test12() { return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53), // (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49), // (14,13): warning CS0162: Unreachable code detected // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13), // (21,22): error CS0841: Cannot use local variable 'x2' before it is declared // return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22), // (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49), // (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope // return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ReturnStatement_02() { var source = @" public class X { public static void Main() { } int Dummy(params object[] x) { return 0;} int Test1(bool val) { if (val) return Dummy(TakeOutParam(true, out var x1)); x1++; return 0; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ReturnStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@" return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(TakeOutParam(""return"", out var x1), x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static object Test(bool val) { if (val) return Dummy(TakeOutParam(""return 1"", out var x2), x2); if (!val) { return Dummy(TakeOutParam(""return 2"", out var x2), x2); } return null; } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return 1 return 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Switch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { switch (TakeOutParam(1, out var x1) ? x1 : 0) { case 0: Dummy(x1, 0); break; } Dummy(x1, 1); } void Test4() { var x4 = 11; Dummy(x4); switch (TakeOutParam(4, out var x4) ? x4 : 0) { case 4: Dummy(x4); break; } } void Test5(int x5) { switch (TakeOutParam(5, out var x5) ? x5 : 0) { case 5: Dummy(x5); break; } } void Test6() { switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) { case 6: Dummy(x6); break; } } void Test7() { switch (TakeOutParam(7, out var x7) ? x7 : 0) { case 7: var x7 = 12; Dummy(x7); break; } } void Test9() { switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 0); switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 1); break; } break; } } void Test10() { switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) { case 10: var y10 = 12; Dummy(y10); break; } } //void Test11() //{ // switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0)) // { // case 11: // let y11 = 12; // Dummy(y11); // break; // } //} void Test14() { switch (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ? 1 : 0) { case 0: Dummy(x14); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (27,41): error CS0128: A local variable named 'x4' is already defined in this scope // switch (TakeOutParam(4, out var x4) ? x4 : 0) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41), // (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(5, out var x5) ? x5 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41), // (47,17): error CS0841: Cannot use local variable 'x6' before it is declared // switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17), // (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21), // (71,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9, 0); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23), // (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(9, out var x9) ? x9 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49), // (85,17): error CS0103: The name 'y10' does not exist in the current context // switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17), // (108,43): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Switch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) switch (TakeOutParam(1, out var x1) ? 1 : 0) { case 0: break; } Dummy(x1, 1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,15): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Switch_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@" switch (Dummy(TakeOutParam(true, out var x1), x1)) {} "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1))) { case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_SwitchLabelGuard_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test1(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 1 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 2 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; } } void Test2(int val) { switch (val) { case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Dummy(x2); break; } } void Test3(int x3, int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x3), x3): Dummy(x3); break; } } void Test4(int val) { var x4 = 11; switch (val) { case 0 when Dummy(TakeOutParam(true, out var x4), x4): Dummy(x4); break; case 1 when Dummy(x4): Dummy(x4); break; } } void Test5(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x5), x5): Dummy(x5); break; } var x5 = 11; Dummy(x5); } //void Test6(int val) //{ // let x6 = 11; // switch (val) // { // case 0 when Dummy(x6): // Dummy(x6); // break; // case 1 when Dummy(TakeOutParam(true, out var x6), x6): // Dummy(x6); // break; // } //} //void Test7(int val) //{ // switch (val) // { // case 0 when Dummy(TakeOutParam(true, out var x7), x7): // Dummy(x7); // break; // } // let x7 = 11; // Dummy(x7); //} void Test8(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test9(int val) { switch (val) { case 0 when Dummy(x9): int x9 = 9; Dummy(x9); break; case 2 when Dummy(x9 = 9): Dummy(x9); break; case 1 when Dummy(TakeOutParam(true, out var x9), x9): Dummy(x9); break; } } //void Test10(int val) //{ // switch (val) // { // case 1 when Dummy(TakeOutParam(true, out var x10), x10): // Dummy(x10); // break; // case 0 when Dummy(x10): // let x10 = 10; // Dummy(x10); // break; // case 2 when Dummy(x10 = 10, x10): // Dummy(x10); // break; // } //} void Test11(int val) { switch (x11 ? val : 0) { case 0 when Dummy(x11): Dummy(x11, 0); break; case 1 when Dummy(TakeOutParam(true, out var x11), x11): Dummy(x11, 1); break; } } void Test12(int val) { switch (x12 ? val : 0) { case 0 when Dummy(TakeOutParam(true, out var x12), x12): Dummy(x12, 0); break; case 1 when Dummy(x12): Dummy(x12, 1); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case 1 when Dummy(TakeOutParam(true, out var x13), x13): Dummy(x13); break; } } void Test14(int val) { switch (val) { case 1 when Dummy(TakeOutParam(true, out var x14), x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test15(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x15), x15): case 1 when Dummy(TakeOutParam(true, out var x15), x15): Dummy(x15); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (30,31): error CS0841: Cannot use local variable 'x2' before it is declared // case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31), // (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x3), x3): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58), // (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x4), x4): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58), // (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x5), x5): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58), // (102,95): error CS0128: A local variable named 'x8' is already defined in this scope // case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95), // (112,31): error CS0841: Cannot use local variable 'x9' before it is declared // case 0 when Dummy(x9): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31), // (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x9), x9): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58), // (144,17): error CS0103: The name 'x11' does not exist in the current context // switch (x11 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17), // (146,31): error CS0103: The name 'x11' does not exist in the current context // case 0 when Dummy(x11): Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31), // (147,23): error CS0103: The name 'x11' does not exist in the current context // Dummy(x11, 0); Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23), // (157,17): error CS0103: The name 'x12' does not exist in the current context // switch (x12 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17), // (162,31): error CS0103: The name 'x12' does not exist in the current context // case 1 when Dummy(x12): Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31), // (163,23): error CS0103: The name 'x12' does not exist in the current context // Dummy(x12, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23), // (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x13), x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58), // (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x14), x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58), // (198,58): error CS0128: A local variable named 'x15' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58), // (198,64): error CS0165: Use of unassigned local variable 'x15' // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(6, x1Ref.Length); for (int i = 0; i < x1Decl.Length; i++) { VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]); } var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(4, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyNotAnOutLocal(model, x4Ref[3]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]); VerifyNotAnOutLocal(model, x5Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(6, x9Ref.Length); VerifyNotAnOutLocal(model, x9Ref[0]); VerifyNotAnOutLocal(model, x9Ref[1]); VerifyNotAnOutLocal(model, x9Ref[2]); VerifyNotAnOutLocal(model, x9Ref[3]); VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(5, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyNotInScope(model, x11Ref[1]); VerifyNotInScope(model, x11Ref[2]); VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(5, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]); VerifyNotInScope(model, x12Ref[3]); VerifyNotInScope(model, x12Ref[4]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]); VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Decl.Length); Assert.Equal(3, x15Ref.Length); for (int i = 0; i < x15Ref.Length; i++) { VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]); } [Fact] public void Scope_SwitchLabelGuard_02() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_03() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): while (TakeOutParam(x1, out var y1) && Print(y1)) break; break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_04() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): do val = 0; while (TakeOutParam(x1, out var y1) && Print(y1)); break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_05() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): lock ((object)TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_06() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): if (TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): switch (TakeOutParam(x1, out var y1)) { default: break; } System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_08() { var source = @" public class X { public static void Main() { foreach (var x in Test(1)) {} } static System.Collections.IEnumerable Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): yield return TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_09() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z1 = x1 > 0 & TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_10() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): a: TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (14,1): warning CS0164: This label has not been referenced // a: TakeOutParam(x1, out var y1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_11() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): return TakeOutParam(x1, out var y1) && Print(y1); System.Console.WriteLine(y1); break; } return false; } static bool Print<T>(T x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (15,17): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_12() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { try { switch (val) { case 1 when TakeOutParam(123, out var x1): throw Dummy(TakeOutParam(x1, out var y1), y1); System.Console.WriteLine(y1); break; } } catch {} return false; } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (17,21): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_13() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_14() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelPattern_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test8(object val) { switch (val) { case int x8 when Dummy(x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case int x13 when Dummy(x13): Dummy(x13); break; } } void Test14(object val) { switch (val) { case int x14 when Dummy(x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test16(object val) { switch (val) { case int x16 when Dummy(x16): case 1 when Dummy(TakeOutParam(true, out var x16), x16): Dummy(x16); break; } } void Test17(object val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x17), x17): case int x17 when Dummy(x17): Dummy(x17); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,64): error CS0128: A local variable named 'x8' is already defined in this scope // when Dummy(x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64), // (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x13 when Dummy(x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22), // (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x14 when Dummy(x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22), // (51,58): error CS0128: A local variable named 'x16' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58), // (51,64): error CS0165: Use of unassigned local variable 'x16' // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64), // (62,22): error CS0128: A local variable named 'x17' is already defined in this scope // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22), // (62,37): error CS0165: Use of unassigned local variable 'x17' // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyNotAnOutLocal(model, x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]); VerifyNotAnOutLocal(model, x13Ref[3]); VerifyNotAnOutLocal(model, x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").Single(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(4, x14Ref.Length); VerifyNotAnOutLocal(model, x14Ref[0]); VerifyNotAnOutLocal(model, x14Ref[1]); VerifyNotAnOutLocal(model, x14Ref[2]); VerifyNotAnOutLocal(model, x14Ref[3]); VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x16Decl = GetOutVarDeclarations(tree, "x16").Single(); var x16Ref = GetReferences(tree, "x16").ToArray(); Assert.Equal(3, x16Ref.Length); for (int i = 0; i < x16Ref.Length; i++) { VerifyNotAnOutLocal(model, x16Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x16Decl); var x17Decl = GetOutVarDeclarations(tree, "x17").Single(); var x17Ref = GetReferences(tree, "x17").ToArray(); Assert.Equal(3, x17Ref.Length); VerifyModelForOutVar(model, x17Decl, x17Ref); } [Fact] public void Scope_ThrowStatement_01() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1() { throw Dummy(TakeOutParam(true, out var x1), x1); { throw Dummy(TakeOutParam(true, out var x1), x1); } throw Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { throw Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { throw Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); throw Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { throw Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // throw Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // throw Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) throw Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) throw Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); throw Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { throw Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52), // (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48), // (21,21): error CS0841: Cannot use local variable 'x2' before it is declared // throw Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21), // (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48), // (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ThrowStatement_02() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1(bool val) { if (val) throw Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ThrowStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@" throw Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(TakeOutParam(""throw"", out var x2), x2); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(TakeOutParam(""throw 1"", out var x2), x2); if (!val) { throw Dummy(TakeOutParam(""throw 2"", out var x2), x2); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Using_01() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49), // (35,22): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53), // (68,35): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35), // (86,35): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (var d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (var d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (var d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72), // (35,45): error CS0841: Cannot use local variable 'x6' before it is declared // using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76), // (68,58): error CS0103: The name 'y10' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58), // (86,58): error CS0103: The name 'y12' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,69): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_04() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,58): error CS0128: A local variable named 'x1' is already defined in this scope // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (12,63): error CS0841: Cannot use local variable 'x1' before it is declared // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63), // (20,73): error CS0128: A local variable named 'x2' is already defined in this scope // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73), // (20,78): error CS0165: Use of unassigned local variable 'x2' // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_Using_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } void Test3() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4)) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void Scope_While_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { while (TakeOutParam(true, out var x1) && x1) { Dummy(x1); } } void Test2() { while (TakeOutParam(true, out var x2) && x2) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); while (TakeOutParam(true, out var x4) && x4) Dummy(x4); } void Test6() { while (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { while (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { while (TakeOutParam(true, out var x8) && x8) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { while (TakeOutParam(true, out var x9) && x9) { Dummy(x9); while (TakeOutParam(true, out var x9) && x9) // 2 Dummy(x9); } } void Test10() { while (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // while (TakeOutParam(y11, out var x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { while (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // while (TakeOutParam(y13, out var x13)) // let y13 = 12; //} void Test14() { while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43), // (35,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47), // (68,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29), // (86,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_While_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) while (TakeOutParam(true, out var x1)) { ; } x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_While_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@" while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) f = false; f = true; if (f) { while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 4"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Yield_01() { var source = @" using System.Collections; public class X { public static void Main() { } object Dummy(params object[] x) { return null;} IEnumerable Test1() { yield return Dummy(TakeOutParam(true, out var x1), x1); { yield return Dummy(TakeOutParam(true, out var x1), x1); } yield return Dummy(TakeOutParam(true, out var x1), x1); } IEnumerable Test2() { yield return Dummy(x2, TakeOutParam(true, out var x2)); } IEnumerable Test3(int x3) { yield return Dummy(TakeOutParam(true, out var x3), x3); } IEnumerable Test4() { var x4 = 11; Dummy(x4); yield return Dummy(TakeOutParam(true, out var x4), x4); } IEnumerable Test5() { yield return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //IEnumerable Test6() //{ // let x6 = 11; // Dummy(x6); // yield return Dummy(TakeOutParam(true, out var x6), x6); //} //IEnumerable Test7() //{ // yield return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} IEnumerable Test8() { yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } IEnumerable Test9(bool y9) { if (y9) yield return Dummy(TakeOutParam(true, out var x9), x9); } IEnumerable Test11() { Dummy(x11); yield return Dummy(TakeOutParam(true, out var x11), x11); } IEnumerable Test12() { yield return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59), // (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55), // (23,28): error CS0841: Cannot use local variable 'x2' before it is declared // yield return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28), // (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55), // (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55), // (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13), // (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13), // (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92), // (72,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_Yield_02() { var source = @" using System.Collections; public class X { public static void Main() { } IEnumerable Test1() { if (true) yield return TakeOutParam(true, out var x1); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Yield_03() { var source = @" using System.Collections; public class X { public static void Main() { } void Dummy(params object[] x) {} IEnumerable Test1() { yield return 0; SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@" yield return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); yield return Dummy(TakeOutParam(""yield2"", out var x2), x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); if (f) { yield return Dummy(TakeOutParam(""yield2"", out var x1), x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_LabeledStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { a: Dummy(TakeOutParam(true, out var x1), x1); { b: Dummy(TakeOutParam(true, out var x1), x1); } c: Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { a: Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { a: Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); a: Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { a: Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); //a: Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ //a: Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) a: Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) a: Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); a: Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { a: Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (12,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1), // (14,1): warning CS0164: This label has not been referenced // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1), // (16,1): warning CS0164: This label has not been referenced // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (21,1): warning CS0164: This label has not been referenced // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (26,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (33,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (38,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x5), x5); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (59,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1), // (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1), // (65,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1), // (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1), // (73,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (80,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x11), x11); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1), // (85,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x12), x12); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_LabeledStatement_02() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) a: Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1), // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9), // (13,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_LabeledStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@" a: b: Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { a: b: c:Test2(Test1(out int x1), x1); System.Console.Write(x1); return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics( // (11,1): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1), // (11,4): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4), // (11,7): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void DataFlow_01() { var text = @" public class Cls { public static void Main() { Test(out int x1, x1); } static void Test(out int x, int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_02() { var text = @" public class Cls { public static void Main() { Test(out int x1, ref x1); } static void Test(out int x, ref int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // ref x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_03() { var text = @" public class Cls { public static void Main() { Test(out int x1); var x2 = 1; } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used // var x2 = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var dataFlow = model.AnalyzeDataFlow(x2Decl); Assert.True(dataFlow.Succeeded); Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString()); Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString()); } [Fact] public void TypeMismatch_01() { var text = @" public class Cls { public static void Main() { Test(out int x1); } static void Test(out short x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short' // Test(out int x1); Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_01() { var text = @" public class Cls { public static void Main() { Test(int x1); Test(ref int x2); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,14): error CS1525: Invalid expression term 'int' // Test(int x1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // Test(int x1); Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18), // (7,18): error CS1525: Invalid expression term 'int' // Test(ref int x2); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // Test(ref int x2); Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22), // (6,18): error CS0103: The name 'x1' does not exist in the current context // Test(int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18), // (7,22): error CS0103: The name 'x2' does not exist in the current context // Test(ref int x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void Parse_02() { var text = @" public class Cls { public static void Main() { Test(out int x1.); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,24): error CS1003: Syntax error, ',' expected // Test(out int x1.); Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_03() { var text = @" public class Cls { public static void Main() { Test(out System.Collections.Generic.IEnumerable<System.Int32>); } static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable // Test(out System.Collections.Generic.IEnumerable<System.Int32>); Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void GetAliasInfo_01() { var text = @" using a = System.Int32; public class Cls { public static void Main() { Test1(out a x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GetAliasInfo_02() { var text = @" using var = System.Int32; public class Cls { public static void Main() { Test1(out var x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void VarIsNotVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out var x) { x = new var() {val = 123}; return null; } static void Test2(object x, var y) { System.Console.WriteLine(y.val); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void VarIsNotVar_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test1' does not exist in the current context // Test1(out var x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9), // (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0 // public int val; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void SimpleVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static void Test2(object x, object y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0103: The name 'Test1' does not exist in the current context // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_03() { var text = @" public class Cls { public static void Main() { Test1(out var x1, out x1); } static object Test1(out int x, out int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // out x1); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_04() { var text = @" public class Cls { public static void Main() { Test1(out var x1, Test1(out x1, 3)); } static object Test1(out int x, int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // Test1(out x1, Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(ref int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_07() { var text = @" public class Cls { public static void Main() { dynamic x = null; Test2(x.Test1(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x.Test1(out var x1), Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_08() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var x1), x1); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_09() { var text = @" public class Cls { public static void Main() { Test2(new System.Action(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,37): error CS0149: Method name expected // Test2(new System.Action(out var x1), Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void ConstructorInitializers_01() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x, object y) { System.Console.WriteLine(y); } public Test2() : this(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : this(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26) ); var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); var typeInfo = model.GetTypeInfo(initializer); var symbolInfo = model.GetSymbolInfo(initializer); var group = model.GetMemberGroup(initializer); Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936 } [Fact] public void ConstructorInitializers_02() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { public Test2(object x, object y) { System.Console.WriteLine(y); } } class Test3 : Test2 { public Test3() : base(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : base(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26) ); } [Fact] public void ConstructorInitializers_03() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} class Test2 { Test2(out int x) { x = 2; } public Test2() : this(out var x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void ConstructorInitializers_04() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} class Test2 { public Test2(out int x) { x = 1; } } class Test3 : Test2 { public Test3() : base(out var x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_05() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(System.Func<object> x) { System.Console.WriteLine(x()); } public Test2() : this(() => { Test1(out var x1); return x1; }) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_06() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_07() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_08() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (23,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(23, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer(); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular) .GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.True(analyzer.ActionFired); } private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer { public bool ActionFired { get; private set; } private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer); } private void Handle(SyntaxNodeAnalysisContext context) { ActionFired = true; var tree = context.Node.SyntaxTree; var model = context.SemanticModel; var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent; SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl)); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0])); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1])); } } [Fact] public void ConstructorInitializers_09() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_10() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_11() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (21,37): error CS0165: Use of unassigned local variable 'x1' // => System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_12() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_13() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_14() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_15() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_16() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_17() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_14() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_15() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var var), var); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var varDecl = GetOutVarDeclaration(tree, "var"); var varRef = GetReferences(tree, "var").Skip(1).Single(); VerifyModelForOutVar(model, varDecl, varRef); } [Fact] public void SimpleVar_16() { var text = @" public class Cls { public static void Main() { if (Test1(out var x1)) { System.Console.WriteLine(x1); } } static bool Test1(out int x) { x = 123; return true; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void VarAndBetterness_01() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); Test2(out var x2, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, string y) { x = 124; System.Console.WriteLine(x); return null; } static object Test2(out int x, string y) { x = 125; System.Console.WriteLine(x); return null; } static object Test2(out short x, object y) { x = 126; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); VerifyModelForOutVar(model, x2Decl); } [Fact] public void VarAndBetterness_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, object y) { x = 124; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)' // Test1(out var x1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.ArgIterator x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_03() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25), // (6,16): 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. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void RestrictedTypes_04() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out System.ArgIterator x1), x1); var x = default(System.ArgIterator); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out System.ArgIterator x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25), // (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // var x = default(System.ArgIterator); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9), // (6,16): 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. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ElementAccess_01() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out var x1]); Test2(x1); Test2(x[out var _]); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25), // (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21), // (9,21): error CS8183: Cannot infer the type of implicitly-typed discard. // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21) ); } [Fact] public void PointerAccess_01() { var text = @" public class Cls { public static unsafe void Main() { int* p = (int*)0; Test2(p[out var x1]); Test2(x1); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25) ); } [Fact] public void ElementAccess_02() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out int x1], x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21), // (7,21): error CS0165: Use of unassigned local variable 'x1' // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21) ); } [Fact] [WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")] public void MissingArgumentAndNamedOutVarArgument() { var source = @"class Program { public static void Main(string[] args) { if (M(s: out var s)) { string s2 = s; } } public static bool M(int i, out string s) { s = i.ToString(); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)' // if (M(s: out var s)) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13) ); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_01() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x); System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_02() { var text = @" public class Cls { public static void Main() { var y = Test1(out int x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_03() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_04() { var text = @" public class Cls { public static void Main() { for (var y = Test1(out var x) + x; y != 0 ; y = 0) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_05() { var text = @" public class Cls { public static void Main() { foreach (var y in new [] {Test1(out var x) + x}) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_06() { var text = @" public class Cls { public static void Main() { Test1(x: 1, out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21), // (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_07() { var text = @" public class Cls { public static void Main() { int x = 0; Test1(y: ref x, y: out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)' // Test1(y: ref x, y: out var y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); var yRef = GetReferences(tree, "y").ToArray(); Assert.Equal(3, yRef.Length); Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString()); VerifyModelForOutVar(model, yDecl, yRef[2]); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamic() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int z]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @"{ // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) //z IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret }"); } [Fact] public void IndexingDynamicWithDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @" { // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret } "); } [Fact] public void IndexingDynamicWithVarDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out var _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23) ); } [Fact] public void IndexingDynamicWithShortDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out _]; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutVar() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.True(x1.Type.IsErrorType()); VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var x = d[out var x1] + x1; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutInt() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void OutVariableDeclarationInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; return 2; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.2 ret } // i = 3; return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.3 stind.i4 ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 4; return 5; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.5 ret } // i = 6; return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.6 stind.i4 ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} x1] + "" "" + x1); ia.P[out {0} x2] = 4; Console.WriteLine(x2); Console.WriteLine(ia[out {0} x3] + "" "" + x3); ia[out {0} x4] = 4; Console.WriteLine(x4); }} }}"; string[] fillIns = new[] { "int", "var" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString()); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString()); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(1, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString()); CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"2 1 3 5 4 6") .VerifyIL("B.Main()", @"{ // Code size 113 (0x71) .maxstack 4 .locals init (int V_0, //x1 int V_1, //x2 int V_2, //x3 int V_3, //x4 int V_4) IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: callvirt ""int IA.P[out int].get"" IL_000d: stloc.s V_4 IL_000f: ldloca.s V_4 IL_0011: call ""string int.ToString()"" IL_0016: ldstr "" "" IL_001b: ldloca.s V_0 IL_001d: call ""string int.ToString()"" IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: dup IL_002d: ldloca.s V_1 IL_002f: ldc.i4.4 IL_0030: callvirt ""void IA.P[out int].set"" IL_0035: ldloc.1 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: dup IL_003c: ldloca.s V_2 IL_003e: callvirt ""int IA.this[out int].get"" IL_0043: stloc.s V_4 IL_0045: ldloca.s V_4 IL_0047: call ""string int.ToString()"" IL_004c: ldstr "" "" IL_0051: ldloca.s V_2 IL_0053: call ""string int.ToString()"" IL_0058: call ""string string.Concat(string, string, string)"" IL_005d: call ""void System.Console.WriteLine(string)"" IL_0062: ldloca.s V_3 IL_0064: ldc.i4.4 IL_0065: callvirt ""void IA.this[out int].set"" IL_006a: ldloc.3 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret }"); } } [ClrOnlyFact] public void OutVariableDiscardInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; System.Console.WriteLine(11); return 111; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x06F ret } // i = 2; System.Console.Write(22); return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.2 stind.i4 ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 3; System.Console.WriteLine(33) return 333; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.3 stind.i4 ldc.i4.s 33 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x14D ret } // i = 4; System.Console.WriteLine(44); return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.s 44 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} _]); ia.P[out {0} _] = 4; Console.WriteLine(ia[out {0} _]); ia[out {0} _] = 4; }} }}"; string[] fillIns = new[] { "int", "var", "" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"11 111 22 33 333 44") .VerifyIL("B.Main()", @" { // Code size 58 (0x3a) .maxstack 3 .locals init (A V_0, //a IA V_1, //ia int V_2) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloca.s V_2 IL_000c: callvirt ""int IA.P[out int].get"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ldloc.1 IL_0018: ldloca.s V_2 IL_001a: ldc.i4.4 IL_001b: callvirt ""void IA.P[out int].set"" IL_0020: nop IL_0021: ldloc.1 IL_0022: ldloca.s V_2 IL_0024: callvirt ""int IA.this[out int].get"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ldloc.1 IL_0030: ldloca.s V_2 IL_0032: ldc.i4.4 IL_0033: callvirt ""void IA.this[out int].set"" IL_0038: nop IL_0039: ret }"); } } [Fact] public void ElementAccess_04() { var text = @" using System.Collections.Generic; public class Cls { public static void Main() { var list = new Dictionary<int, long> { [out var x1] = 3, [out var _] = 4, [out _] = 5 }; System.Console.Write(x1); System.Console.Write(_); { int _ = 1; var list2 = new Dictionary<int, long> { [out _] = 6 }; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var x1] = 3, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18), // (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var _] = 4, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18), // (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out _] = 5 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18), // (14,30): error CS0103: The name '_' does not exist in the current context // System.Console.Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30), // (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword // var list2 = new Dictionary<int, long> { [out _] = 6 }; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58) ); } [Fact] public void ElementAccess_05() { var text = @" public class Cls { public static void Main() { int[out var x1] a = null; // fatal syntax error - 'out' is skipped int b(out var x2) = null; // parsed as a local function with syntax error int c[out var x3] = null; // fatal syntax error - 'out' is skipped int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator x4 = 0; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count()); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); compilation.VerifyDiagnostics( // (6,13): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13), // (6,21): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21), // (7,27): error CS1002: ; expected // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27), // (7,27): error CS1525: Invalid expression term '=' // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27), // (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14), // (8,15): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15), // (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19), // (8,23): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23), // (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23), // (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17), // (10,17): error CS1003: Syntax error, '[' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17), // (10,28): error CS1003: Syntax error, ']' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28), // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12), // (6,17): error CS0103: The name 'var' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17), // (6,21): error CS0103: The name 'x1' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21), // (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body. // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13), // (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19), // (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29), // (8,19): error CS0103: The name 'var' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19), // (8,23): error CS0103: The name 'x3' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23), // (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13), // (6,25): warning CS0219: The variable 'a' is assigned but its value is never used // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25), // (10,13): warning CS0168: The variable 'd' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13), // (10,16): warning CS0168: The variable 'e' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16), // (7,13): warning CS8321: The local function 'b' is declared but never used // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13) ); } [Fact] public void ElementAccess_06() { var text = @" public class Cls { public static void Main() { { int[] e = null; var z1 = e?[out var x1]; x1 = 1; } { int[][] e = null; var z2 = e?[out var x2]?[out var x3]; x2 = 1; x3 = 2; } { int[][] e = null; var z3 = e?[0]?[out var x4]; x4 = 1; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var x2Decl = GetOutVarDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29), // (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33), // (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29), // (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'. // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33), // (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33), // (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'. // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37) ); } [Fact] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[out var x1, x1]; //fixed int F2[3 is int x2 ? x2 : 3]; //fixed int F2[3 is int x3 ? 3 : 3, x3]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Empty(GetOutVarDeclarations(tree, "x1")); compilation.VerifyDiagnostics( // (4,18): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18), // (4,26): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26), // (4,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17), // (4,22): error CS0103: The name 'var' does not exist in the current context // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22) ); } [Fact] public void Scope_DeclaratorArguments_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { int d,e(Dummy(TakeOutParam(true, out var x1), x1)); } void Test4() { var x4 = 11; Dummy(x4); int d,e(Dummy(TakeOutParam(true, out var x4), x4)); } void Test6() { int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); } void Test8() { int d,e(Dummy(TakeOutParam(true, out var x8), x8)); System.Console.WriteLine(x8); } void Test14() { int d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // int d,e(Dummy(TakeOutParam(true, out var x4), x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (30,34): error CS0165: Use of unassigned local variable 'x8' // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl) { Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl)); } private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls) { foreach (var decl in decls) { AssertContainedInDeclaratorArguments(decl); } } [Fact] public void Scope_DeclaratorArguments_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d, x1( Dummy(TakeOutParam(true, out var x1), x1)); Dummy(x1); } void Test2() { object d, x2( Dummy(TakeOutParam(true, out var x2), x2)); Dummy(x2); } void Test3() { object x3, d( Dummy(TakeOutParam(true, out var x3), x3)); Dummy(x3); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,13): error CS0818: Implicitly-typed variables must be initialized // var d, x1( Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13), // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (21,15): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15), // (27,54): error CS0128: A local variable named 'x3' is already defined in this scope // Dummy(TakeOutParam(true, out var x3), x3)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54), // (28,15): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1( Dummy(x1)); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2(Dummy(x3)); } void Test4() { object d1,e(Dummy(x4)], d2(Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1( Dummy(x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (14,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1,e(Dummy(x4)], Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 (Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (13,27): error CS0165: Use of unassigned local variable 'x1' // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59), // (26,27): error CS0165: Use of unassigned local variable 'x3' // d2 = Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y, y1(Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single(); Assert.Equal("var y1", y1.ToTestDisplayString()); Assert.True(((ILocalSymbol)y1).Type.IsErrorType()); } [Fact] public void Scope_DeclaratorArguments_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d,e(TakeOutParam(true, out var x1) && x1 != null); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13), // (11,17): error CS0818: Implicitly-typed variables must be initialized // var d,e(TakeOutParam(true, out var x1) && x1 != null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e); Assert.Equal("var e", symbol.ToTestDisplayString()); Assert.True(symbol.Type.IsErrorType()); } [Fact] [WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")] public void Scope_DeclaratorArguments_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)]; System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); AssertContainedInDeclaratorArguments(y1Decl); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType()); } [Fact] [WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")] public void Scope_DeclaratorArguments_08() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool a, b( Dummy(TakeOutParam(true, out var x1) && x1) );;) { Dummy(x1); } } void Test2() { for (bool a, b( Dummy(TakeOutParam(true, out var x2) && x2) );;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool a, b( Dummy(TakeOutParam(true, out var x4) && x4) );;) Dummy(x4); } void Test6() { for (bool a, b( Dummy(x6 && TakeOutParam(true, out var x6)) );;) Dummy(x6); } void Test7() { for (bool a, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool a, b( Dummy(TakeOutParam(true, out var x8) && x8) );;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool a1, b1( Dummy(TakeOutParam(true, out var x9) && x9) );;) { Dummy(x9); for (bool a2, b2( Dummy(TakeOutParam(true, out var x9) && x9) // 2 );;) Dummy(x9); } } void Test10() { for (bool a, b( Dummy(TakeOutParam(y10, out var x10)) );;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool a, b( // Dummy(TakeOutParam(y11, out var x11)) // );;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool a, b( Dummy(TakeOutParam(y12, out var x12)) );;) var y12 = 12; } //void Test13() //{ // for (bool a, b( // Dummy(TakeOutParam(y13, out var x13)) // );;) // let y13 = 12; //} void Test14() { for (bool a, b( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) );;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_09() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { for (bool d, x4( Dummy(TakeOutParam(true, out var x4) && x4) );;) {} } void Test7() { for (bool x7 = true, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) {} } void Test8() { for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)], b2(Dummy(TakeOutParam(true, out var x8) && x8)); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2(Dummy(TakeOutParam(true, out var x9) && x9)); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47), // (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47), // (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used // for (bool x7 = true, b( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19), // (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2(Dummy(TakeOutParam(true, out var x8) && x8)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52), // (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47), // (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47), // (37,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23), // (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47), // (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl[0]); AssertContainedInDeclaratorArguments(x8Decl[1]); VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]); } [Fact] public void Scope_DeclaratorArguments_10() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,e(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (var d,e(Dummy(TakeOutParam(true, out var x2), x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Dummy(x4); } void Test6() { using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d,e(Dummy(TakeOutParam(true, out var x8), x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d,a(Dummy(TakeOutParam(true, out var x9), x9))) { Dummy(x9); using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Dummy(x9); } } void Test10() { using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) var y12 = 12; } //void Test13() //{ // using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13))) // let y13 = 12; //} void Test14() { using (var d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); AssertContainedInDeclaratorArguments(x10Decl); VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_11() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope // using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope // using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); AssertContainedInDeclaratorArguments(x2Decl); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_DeclaratorArguments_12() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } void Test3() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2(Dummy(TakeOutParam(true, out var x4), x4))) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_13() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Dummy(x4); } void Test6() { fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9))) { Dummy(x9); fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Dummy(x9); } } void Test10() { fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11)))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) var y12 = 12; } //void Test13() //{ // fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13)))) // let y13 = 12; //} void Test14() { fixed (int* p,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_14() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* d,x1( Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)], x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p(Dummy(TakeOutParam(true, out var x3) && x3))) { Dummy(x3); } } void Test4() { fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)], p2(Dummy(TakeOutParam(true, out var x4) && x4))) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Scope_DeclaratorArguments_15() { var source = @" public class X { public static void Main() { } bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; bool Test4 [x4 && TakeOutParam(4, out var x4)]; bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } private static void VerifyModelNotSupported( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax)); Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var identifierText = decl.Identifier().ValueText; Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any()); Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText)); Assert.Null(model.GetSymbolInfo(decl.Type).Symbol); AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null); VerifyModelNotSupported(model, references); } private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references) { foreach (var reference in references) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart)); Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType()); } } [Fact] public void Scope_DeclaratorArguments_16() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; fixed bool Test4 [x4 && TakeOutParam(4, out var x4)]; fixed bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; fixed bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; fixed bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; fixed bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField, (int)ErrorCode.ERR_NoImplicitConv }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 [x4 && TakeOutParam(4, out var x4)]; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (20,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 [Dummy(x7, 2)]; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25), // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_17() { var source = @" public class X { public static void Main() { } const bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; const bool Test4 [x4 && TakeOutParam(4, out var x4)]; const bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; const bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; const bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; const bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_18() { var source = @" public class X { public static void Main() { } event bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; event bool Test4 [x4 && TakeOutParam(4, out var x4)]; event bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; event bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; event bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; event bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.ERR_EventNotDelegate, (int)ErrorCode.WRN_UnreferencedEvent }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_19() { var source = @" public unsafe struct X { public static void Main() { } fixed bool d[2], Test3 (out var x3); } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (8,28): error CS1003: Syntax error, '[' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28), // (8,39): error CS1003: Syntax error, ']' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39), // (8,33): error CS8185: A declaration is not allowed in this context. // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_20() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3[out var x3]; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,22): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22), // (8,30): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30), // (8,21): error CS7092: A fixed buffer may only have one dimension. // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21), // (8,26): error CS0103: The name 'var' does not exist in the current context // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); } [Fact] public void StaticType() { var text = @" public class Cls { public static void Main() { Test1(out StaticType x1); } static object Test1(out StaticType x) { throw new System.NotSupportedException(); } static class StaticType {} }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters // static object Test1(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19), // (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType' // Test1(out StaticType x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19) ); } [Fact] public void GlobalCode_Catch_01() { var source = @" bool Dummy(params object[] x) {return true;} try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34), // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42), // (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13), // (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Catch_02() { var source = @" try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Block_01() { string source = @" { H.TakeOutParam(1, out var x1); H.Dummy(x1); } object x2; { H.TakeOutParam(2, out var x2); H.Dummy(x2); } { H.TakeOutParam(3, out var x3); } H.Dummy(x3); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,8): warning CS0168: The variable 'x2' is declared but never used // object x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8), // (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31), // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } } [Fact] public void GlobalCode_Block_02() { string source = @" { H.TakeOutParam(1, out var x1); System.Console.WriteLine(x1); Test(); void Test() { System.Console.WriteLine(x1); } } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_For_01() { var source = @" bool Dummy(params object[] x) {return true;} for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } for ( // 2 Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42), // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_For_02() { var source = @" bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_Foreach_01() { var source = @"using static Helpers; System.Collections.IEnumerable Dummy(params object[] x) {return null;} foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } static class Helpers { public static bool TakeOutParam(int y, out int x) { x = y; return true; } public static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Foreach_02() { var source = @" bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_01() { var source = @" bool Dummy(params object[] x) {return true;} Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0)); Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) && TakeOutParam(o2, out var x5) && x5 > 0)); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0)); Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0), x7); Dummy(x7, 2); Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out var x9) && x9 > 0), x9); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) && x10 > 0), TakeOutParam(true, out var x10), x10); var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) && x11 > 0), x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutField(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutField(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutField(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7), // (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7), // (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79), // (37,9): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9), // (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13), // (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void GlobalCode_Lambda_02() { var source = @" System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); System.Console.WriteLine(l()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_03() { var source = @" System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Query_01() { var source = @" using System.Linq; bool Dummy(params object[] x) {return true;} var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutField(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutField(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutField(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutField(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutField(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutField(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutField(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutField(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutField(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutField(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutField(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutField(model, y10Decl, y10Ref[0]); VerifyNotAnOutField(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutField(model, y11Decl, y11Ref[0]); VerifyNotAnOutField(model, y11Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7), // (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18), // (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } } [Fact] public void GlobalCode_Query_02() { var source = @" using System.Linq; var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutField(model, yDecl, yRef); } [Fact] public void GlobalCode_Using_01() { var source = @" System.IDisposable Dummy(params object[] x) {return null;} using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_Using_02() { var source = @" using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void GlobalCode_ExpressionStatement_01() { string source = @" H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out int x2); H.TakeOutParam(3, out int x3); object x3; H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } private static void AssertNoGlobalStatements(SyntaxTree tree) { Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()); } [Fact] public void GlobalCode_ExpressionStatement_02() { string source = @" H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out var x2); H.TakeOutParam(3, out var x3); object x3; H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ExpressionStatement_03() { string source = @" System.Console.WriteLine(x1); H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_IfStatement_01() { string source = @" if (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out int x2)) {} if (H.TakeOutParam(3, out int x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} if (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); int x6 = 6; if (H.Dummy()) { string x6 = ""6""; H.Dummy(x6); } void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (30,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17), // (30,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21), // (30,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used // int x6 = 6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5), // (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x6 = "6"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12), // (33,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_IfStatement_02() { string source = @" if (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out var x2)) {} if (H.TakeOutParam(3, out var x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} void Test() { H.Dummy(x1, x2, x3, x4, x5); } if (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,29): error CS0841: Cannot use local variable 'x5' before it is declared // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29), // (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } } [Fact] public void GlobalCode_IfStatement_03() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_IfStatement_04() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_YieldReturnStatement_01() { string source = @" yield return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out int x2); yield return H.TakeOutParam(3, out int x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_YieldReturnStatement_02() { string source = @" yield return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out var x2); yield return H.TakeOutParam(3, out var x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_01() { string source = @" return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out int x2); return H.TakeOutParam(3, out int x3); object x3; return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_02() { string source = @" return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out var x2); return H.TakeOutParam(3, out var x3); object x3; return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_03() { string source = @" System.Console.WriteLine(x1); Test(); return H.Dummy(H.TakeOutParam(1, out var x1), x1); void Test() { System.Console.WriteLine(x1); } class H { public static bool Dummy(object x, object y) { System.Console.WriteLine(y); return true; } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_ThrowStatement_01() { string source = @" throw H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out int x2); throw H.TakeOutParam(3, out int x3); object x3; throw H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ThrowStatement_02() { string source = @" throw H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out var x2); throw H.TakeOutParam(3, out var x3); object x3; throw H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_SwitchStatement_01() { string source = @" switch (H.TakeOutParam(1, out int x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out int x2)) {default: break;} switch (H.TakeOutParam(3, out int x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {default: break;} switch (H.TakeOutParam(51, out int x5)) { default: H.TakeOutParam(""52"", out string x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_02() { string source = @" switch (H.TakeOutParam(1, out var x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out var x2)) {default: break;} switch (H.TakeOutParam(3, out var x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {default: break;} switch (H.TakeOutParam(51, out var x5)) { default: H.TakeOutParam(""52"", out var x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_03() { string source = @" System.Console.WriteLine(x1); switch (H.TakeOutParam(1, out var x1)) { default: H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); break; } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_WhileStatement_01() { string source = @" while (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out int x2)) {} while (H.TakeOutParam(3, out int x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} while (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out int x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_02() { string source = @" while (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out var x2)) {} while (H.TakeOutParam(3, out var x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} while (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out var x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_03() { string source = @" while (H.TakeOutParam(1, out var x1)) { System.Console.WriteLine(x1); break; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_DoStatement_01() { string source = @" do {} while (H.TakeOutParam(1, out int x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out int x2)); do {} while (H.TakeOutParam(3, out int x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))); do { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } while (H.TakeOutParam(51, out int x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out int x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out int x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_02() { string source = @" do {} while (H.TakeOutParam(1, out var x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out var x2)); do {} while (H.TakeOutParam(3, out var x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))); do { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } while (H.TakeOutParam(51, out var x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out var x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out var x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_03() { string source = @" int f = 1; do { } while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3); int Test(int x) { System.Console.WriteLine(x); return x; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2 3").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_LockStatement_01() { string source = @" lock (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out int x2)) {} lock (H.TakeOutParam(3, out int x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} lock (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_02() { string source = @" lock (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out var x2)) {} lock (H.TakeOutParam(3, out var x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} lock (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_03() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_LockStatement_04() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_DeconstructionDeclarationStatement_01() { string source = @" (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); Test(); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (16,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref[0]); } } [Fact] public void GlobalCode_LabeledStatement_01() { string source = @" a: H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out int x2); c: H.TakeOutParam(3, out int x3); object x3; d: H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_02() { string source = @" a: H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out var x2); c: H.TakeOutParam(3, out var x3); object x3; d: H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_03() { string source = @" System.Console.WriteLine(x1); a:b:c:H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_04() { string source = @" a: bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out int x2); e: bool f = H.TakeOutParam(3, out int x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); i: bool x5 = H.TakeOutParam(5, out int x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [Fact] public void GlobalCode_LabeledStatement_05() { string source = @" a: bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out var x2); e: bool f = H.TakeOutParam(3, out var x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); i: bool x5 = H.TakeOutParam(5, out var x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void GlobalCode_LabeledStatement_06_Script() { string source = @" System.Console.WriteLine(x1); a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_06_SimpleProgram() { string source = @" a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_07() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_08() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out var x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out var x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), H.TakeOutParam(6, out var x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_09() { string source = @" System.Console.WriteLine(x1); a:b:c: var (d, e) = (H.TakeOutParam(1, out var x1), 1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_01() { string source = @" bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out int x2); bool f = H.TakeOutParam(3, out int x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 = H.TakeOutParam(5, out int x5); bool i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_02() { string source = @" bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out var x2); bool f = H.TakeOutParam(3, out var x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 = H.TakeOutParam(5, out var x5); bool i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_03() { string source = @" System.Console.WriteLine(x1); var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static var b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_05() { string source = @" bool b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_06() { string source = @" bool b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_07() { string source = @" Test(); bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); bool Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return false; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_PropertyDeclaration_01() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out int x2); bool f { get; } = H.TakeOutParam(3, out int x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 { get; } = H.TakeOutParam(5, out int x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_02() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out var x2); bool f { get; } = H.TakeOutParam(3, out var x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 { get; } = H.TakeOutParam(5, out var x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_03() { string source = @" System.Console.WriteLine(x1); bool d { get; set; } = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static bool b { get; } = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_05() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_06() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_01() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out int x2); event System.Action f = H.TakeOutParam(3, out int x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); event System.Action x5 = H.TakeOutParam(5, out int x5); event System.Action i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_02() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out var x2); event System.Action f = H.TakeOutParam(3, out var x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); event System.Action x5 = H.TakeOutParam(5, out var x5); event System.Action i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_03() { string source = @" System.Console.WriteLine(x1); event System.Action d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static event System.Action b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_05() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_06() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_07() { string source = @" Test(); event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); System.Action Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_DeclaratorArguments_01() { string source = @" bool a, b(out var x1); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_02() { string source = @" label: bool a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1), // (4,9): error CS0165: Use of unassigned local variable 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_03() { string source = @" event System.Action a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static System.Action Dummy(params object[] x) {return null;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_DeclaratorArguments_04() { string source = @" fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static int TakeOutParam<T>(T y, out T x) { x = y; return 3; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to 'b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12), // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_RestrictedType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out System.ArgIterator x2); class H { public static void TakeOutParam(out System.ArgIterator x) { x = default(System.ArgIterator); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public static void TakeOutParam(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37), // (5,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out System.ArgIterator x2); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20), // (3,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_StaticType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out StaticType x2); class H { public static void TakeOutParam(out StaticType x) { x = default(System.ArgIterator); } } static class StaticType{} "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (5,31): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out StaticType x2); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31), // (9,24): error CS0721: 'StaticType': static types cannot be used as parameters // public static void TakeOutParam(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24), // (3,24): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_InferenceFailure_01() { string source = @" H.TakeOutParam(out var x1, x1); class H { public static void TakeOutParam(out int x, long y) { x = 1; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.TakeOutParam(out var x1, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact] public void GlobalCode_InferenceFailure_02() { string source = @" var a = b; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_03() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = a; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = a; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_04() { string source = @" var a = x1; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single()); Assert.True(a.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32) ); } [Fact] public void GlobalCode_InferenceFailure_05() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = x1; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = H.TakeOutParam(out var x1, b); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single(); var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl); Assert.True(b.Type.IsErrorType()); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); Assert.False(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); } [Fact] public void GlobalCode_InferenceFailure_06() { string source = @" H.TakeOutParam(out var x1); class H { public static int TakeOutParam<T>(out T x) { x = default(T); return 123; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24), // (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3) ); compilation.GetDeclarationDiagnostics().Verify( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")] public void GlobalCode_InferenceFailure_07() { string source = @" H.M((var x1, int x2)); H.M(x1); class H { public static void M(object a) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10), // (2,6): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6), // (2,14): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14), // (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5), // (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object' // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5) ); compilation.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")] public void InferenceFailure_01() { string source = @" class H { object M1() => M(M(1), x1); static object M(object o1) => o1; static void M(object o1, object o2) {} } "; var node0 = SyntaxFactory.ParseCompilationUnit(source); var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var decl = SyntaxFactory.DeclarationExpression( type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")), designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1"))); var node1 = node0.ReplaceNode(one, decl); var tree = node1.SyntaxTree; Assert.NotNull(tree); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics( // (4,24): error CS8185: A declaration is not allowed in this context. // object M1() => M(M(varx1), x1); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24) ); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_AliasInfo_01() { string source = @" H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void GlobalCode_AliasInfo_02() { string source = @" using var = System.Int32; H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_03() { string source = @" using a = System.Int32; H.TakeOutParam(1, out a x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_04() { string source = @" H.TakeOutParam(1, out int x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_1() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out var x1): System.Console.WriteLine(x1); break; } } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case !TakeOutParam(3, out var x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_2() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out UndeclaredType x1): System.Console.WriteLine(x1); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19), // (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?) // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, false, references); } private static void VerifyModelForOutFieldDuplicate( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, true, references); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, bool duplicate, params IdentifierNameSyntax[] references) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(SymbolKind.Field, symbol.Kind); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText); var names = model.LookupNames(decl.SpanStart); if (duplicate) { Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, symbols.Single()); } Assert.Contains(decl.Identifier().ValueText, names); var local = (IFieldSymbol)symbol; var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement && (declarator.ArgumentList?.Contains(decl)).GetValueOrDefault(); // We're not able to get type information at such location (out var argument in global code) at this point // See https://github.com/dotnet/roslyn/issues/13569 AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type); foreach (var reference in references) { var referenceInfo = model.GetSymbolInfo(reference); symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText); if (duplicate) { Assert.Null(referenceInfo.Symbol); Assert.Contains(symbol, referenceInfo.CandidateSymbols); Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, referenceInfo.Symbol); Assert.Same(symbol, symbols.Single()); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); } if (!inFieldDeclaratorArgumentlist) { var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent; if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); } else { var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (dataFlow.Succeeded) { Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } } [Fact] public void MethodTypeArgumentInference_01() { var source = @" public class X { public static void Main() { TakeOutParam(out int a); TakeOutParam(out long b); } static void TakeOutParam<T>(out T x) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int64"); } [Fact] public void MethodTypeArgumentInference_02() { var source = @" public class X { public static void Main() { TakeOutParam(out var a); } static void TakeOutParam<T>(out T x) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out var a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9) ); } [Fact] public void MethodTypeArgumentInference_03() { var source = @" public class X { public static void Main() { long a = 0; TakeOutParam(out int b, a); int c; TakeOutParam(out c, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out int b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9), // (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out c, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9) ); } [Fact] public void MethodTypeArgumentInference_04() { var source = @" public class X { public static void Main() { byte a = 0; int b = 0; TakeOutParam(out int c, a); TakeOutParam(out b, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int32"); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void OutVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); } [Fact] public void OutVarDiscard() { var source = @" public class C { static void Main() { M(out int _); M(out var _); M(out _); } static void M(out int x) { x = 1; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.Single(); var model = comp.Compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); 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.GetTypeInfo(discard2).Type); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); comp.VerifyIL("C.Main()", @" { // Code size 22 (0x16) .maxstack 1 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: call ""void C.M(out int)"" IL_0007: ldloca.s V_0 IL_0009: call ""void C.M(out int)"" IL_000e: ldloca.s V_0 IL_0010: call ""void C.M(out int)"" IL_0015: ret } "); } [Fact] public void NamedOutVarDiscard() { var source = @" public class C { static void Main() { M(y: out string _, x: out int _); M(y: out var _, x: out var _); M(y: out _, x: out _); } static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); } [Fact] public void OutVarDiscardInCtor_01() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out int i1); new C(out int _); new C(out var _); new C(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); 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); Assert.Equal("int", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); 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("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact] public void OutVarDiscardInCtor_02() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out long x1); new C(out long _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long x1); Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19), // (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long _); Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19), // (7,19): error CS0165: Use of unassigned local variable 'x1' // new C(out long x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl); var discard1 = GetDiscardDesignations(tree).Single(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("long _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("long", declaration1.Type.ToString()); Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); } [Fact] public void OutVarDiscardAliasInfo_01() { var source = @" using alias1 = System.Int32; using var = System.Int32; public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString()); 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("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString()); } [Fact] public void OutVarDiscardAliasInfo_02() { var source = @" enum alias1 : long {} class var {} public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int' // new C(out alias1 _); Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19), // (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int' // new C(out var _); Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString()); Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); 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("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("var", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); } [Fact] public void OutVarDiscardInCtorInitializer() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C ""); } static void Main() { new Derived2(out int i2); new Derived3(out int i3); new Derived4(); } } public class Derived2 : C { public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); } } public class Derived3 : C { public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); } } public class Derived4 : C { public Derived4(out int i) : base(out _) { i = 4; } public Derived4() : this(out _) { System.Console.Write(""Derived4""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4"); } [Fact] public void DiscardNotRecognizedInOtherScenarios() { var source = @" public class C { void M<T>() { _.ToString(); M(_); _<T>.ToString(); (_<T>, _<T>) = (1, 2); M<_>(); new C() { _ = 1 }; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): error CS0103: The name '_' does not exist in the current context // _.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9), // (7,11): error CS0103: The name '_' does not exist in the current context // M(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11), // (8,9): error CS0103: The name '_' does not exist in the current context // _<T>.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9), // (9,10): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10), // (9,16): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16), // (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // M<_>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11), // (11,19): error CS0117: 'C' does not contain a definition for '_' // new C() { _ = 1 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19) ); } [Fact] public void TypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); System.Console.Write(t.GetType().ToString()); } static void Main() { M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "System.Int32"); } [Fact] public void UntypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); } static void Main() { M(out var _); M(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out var _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9), // (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9) ); } [Fact] public void PickOverloadWithTypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); } static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); } static void Main() { M(out object _); M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "object returning M. int returning M."); } [Fact] public void CannotPickOverloadWithUntypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; } static void M(out int x) { x = 2; } static void Main() { M(out var _); M(out _); M(out byte _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out var _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9), // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9), // (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object' // M(out byte _); Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15) ); } [Fact] public void NoOverloadWithDiscard() { var source = @" public class A { } public class B : A { static void M(A a) { a.M2(out A x); a.M2(out A _); } } public static class S { public static void M2(this A self, out B x) { x = null; } }"; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore }); comp.VerifyDiagnostics( // (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A x); Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18), // (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A _); Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18) ); } [Fact] [WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")] public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier() { var source = @" public class C { static void M(string x) { if(true) && int.TryParse(x, out int y)) id(iVal); // Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single(); Assert.Equal("x", x.ToString()); Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString()); } [Fact] public void DuplicateDeclarationInSwitchBlock() { var text = @" public class C { public static void Main(string[] args) { switch (args.Length) { case 0: M(M(out var x1), x1); M(M(out int x1), x1); break; case 1: M(M(out int x1), x1); break; } } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics( // (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29), // (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29), // (13,34): error CS0165: Use of unassigned local variable 'x1' // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x6Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x6Decl.Length); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]); } [Fact] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(int a, int b) => a+b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,75): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,75): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInAnonymousMethodParameterDefault() { var text = @" class C { public static void Main(int arg) { System.Action<bool, int> d1 = delegate ( bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }; System.Action<bool, int> d2 = delegate ( bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }; int x = z1 + z2; d1 = d2 = null; } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; } "; // the scope of an expression variable introduced in the default expression // of a lambda parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify( // (9,55): error CS0103: The name 'z1' does not exist in the current context // { var t = z1; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55), // (13,55): error CS0103: The name 'z2' does not exist in the current context // { var t = z2; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55), // (15,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17), // (15,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First(); Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString()); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void Scope_LocalFunction_Attribute_01() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_02() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_03() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_04() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_05() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_LocalFunction_Attribute_06() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_InvalidArrayDimensions01() { var text = @" public class Cls { public static void Main() { int x1 = 0; int[Test1(out int x1), x1] _1; int[Test1(out int x2), x2] x2; } static int Test1(out int x) { x = 1; return 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12), // (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27), // (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12), // (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13), // (7,27): warning CS0168: The variable 'x1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27), // (7,36): warning CS0168: The variable '_1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36), // (8,27): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27), // (8,36): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyNotAnOutLocal(model, x1Ref); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref); } [Fact] public void Scope_InvalidArrayDimensions_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using (int[] d = null) { Dummy(x1); } } void Test2() { using (int[] d = null) Dummy(x2); } void Test3() { var x3 = 11; Dummy(x3); using (int[] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 3; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16), // file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19), // file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // file.cs(14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16), // file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19), // file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51), // file.cs(21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16), // file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19), // file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51), // file.cs(30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using int[TakeOutParam(true, out var x1), x1] d = null; Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); using int[TakeOutParam(true, out var x2), x2] d = null; Dummy(x2); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9), // (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18), // (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19), // (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // (13,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15), // (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9), // (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18), // (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19), // (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46), // (21,46): warning CS0168: The variable 'x2' is declared but never used // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyNotAnOutLocal(model, x2Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true); } [Fact] public void Scope_InvalidArrayDimensions_04() { var source = @" public class X { public static void Main() { } bool Dummy(object x) {return true;} void Test1() { for (int[] a = null;;) Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); for (int[] a = null;;) Dummy(x2); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 2; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17), // file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18), // file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49), // file.cs(13,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19), // file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53), // file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17), // file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45), // file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18), // file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49), // file.cs(22,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19), // file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} unsafe void Test1() { fixed (int[TakeOutParam(true, out var x1), x1] d = null) { Dummy(x1); } } unsafe void Test2() { fixed (int[TakeOutParam(true, out var x2), x2] d = null) Dummy(x2); } unsafe void Test3() { var x3 = 11; Dummy(x3); fixed (int[TakeOutParam(true, out var x3), x3] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test1() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17), // (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19), // (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52), // (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56), // (14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test2() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17), // (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19), // (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52), // (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56), // (21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test3() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17), // (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19), // (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52), // (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56), // (30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void DeclarationInNameof_00() { var text = @" class C { public static void Main() { var x = nameof(M2(M1(out var x1), x1)).ToString(); } static int M1(out int z) => z = 1; static int M2(int a, int b) => 2; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,24): error CS8081: Expression does not have a name. // var x = nameof(M2(M1(out var x1), x1)).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "x1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(1, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DeclarationInNameof_01() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(object a, int b) => b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,83): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83), // (6,39): error CS8081: Expression does not have a name. // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30), // (6,69): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69), // (7,83): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83), // (7,39): error CS8081: Expression does not have a name. // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30), // (7,69): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02a() { var text = @" [My(C.M(nameof(C.M(out int z1)), z1), z1)] [My(C.M(nameof(C.M(out var z2)), z2), z2)] class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (2,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16), // (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5), // (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39), // (3,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16), // (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5), // (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02b() { var text1 = @" [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] "; var text2 = @" class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 }); compilation.VerifyDiagnostics( // (2,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26), // (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15), // (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49), // (3,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26), // (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15), // (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_03() { var text = @" class C { public static void Main(string[] args) { switch ((object)args.Length) { case !M(nameof(M(out int z1)), z1): System.Console.WriteLine(z1); break; case !M(nameof(M(out var z2)), z2): System.Console.WriteLine(z2); break; } } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (8,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28), // (8,18): error CS0150: A constant value is expected // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18), // (11,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28), // (11,18): error CS0150: A constant value is expected // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18), // (8,44): error CS0165: Use of unassigned local variable 'z1' // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44), // (11,44): error CS0165: Use of unassigned local variable 'z2' // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_04() { var text = @" class C { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); const bool c = (z1 + z2) == 0; public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (5,29): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29), // (5,20): error CS0133: The expression being assigned to 'C.b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20), // (6,21): error CS0103: The name 'z1' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21), // (6,26): error CS0103: The name 'z2' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26), // (4,29): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29), // (4,20): error CS0133: The expression being assigned to 'C.a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_05() { var text = @" class C { public static void Main(string[] args) { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); bool c = (z1 + z2) == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,33): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33), // (6,24): error CS0133: The expression being assigned to 'a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24), // (7,33): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33), // (7,24): error CS0133: The expression being assigned to 'b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24), // (6,49): error CS0165: Use of unassigned local variable 'z1' // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49), // (7,49): error CS0165: Use of unassigned local variable 'z2' // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_06() { var text = @" class C { public static void Main(string[] args) { string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); bool c = z1 == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,27): error CS8081: Expression does not have a name. // string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27), // (7,18): error CS0103: The name 'z1' does not exist in the current context // bool c = z1 == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "z1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVar(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_01() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p => { weakRef.TryGetTarget(out var x); }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_02() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { weakRef.TryGetTarget(out var x); }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_03() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { void Local1 (Action<T> onNext = p3 => { weakRef.TryGetTarget(out var x); }) { } }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_04() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_05() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select (Action<T>)( p => { void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } ) ) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_06() { string source = @" class C { void M<T>() { System.Type t = typeof(int[p => { weakRef.TryGetTarget(out var x); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_07() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { weakRef.TryGetTarget(out var x); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_08() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { System.Type t3 = typeof(int[p3 => { weakRef.TryGetTarget(out var x); }]); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_09() { string source = @" class C { void M<T>() { System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_10() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[from p in y select (Action<T>)( p => { System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } ) ] ); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")] public void GetEnclosingBinderInternalRecovery_11() { var text = @" class Program { static void Main(string[] args) { foreach other(some().F(a => TestOutVar(out var x) ? x : 1)); } static void TestOutVar(out int a) { a = 0; } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, '(' expected // foreach Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16), // (7,60): error CS1515: 'in' expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60), // (7,60): error CS0230: Type and identifier are both required in a foreach statement // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60), // (7,60): error CS1525: Invalid expression term ';' // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60), // (7,60): error CS1026: ) expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xDecl = GetOutVarDeclaration(tree, "x"); var xRef = GetReferences(tree, "x", 1); VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString()); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates() { var source = @"using System; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Func<int, bool> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Expression() { var source = @"using System; using System.Linq.Expressions; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Expression<Func<int, bool>> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Query() { var source = @"using System.Linq; class C { static void M() { var c = from x in new[] { 1, 2, 3 } group x > 1 && F(out var y) && y == null by x; } static bool F(out object o) { o = null; return true; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public void SpeculativeSemanticModelWithOutDiscard() { var source = @"class C { static void F() { C.G(out _); } static void G(out object o) { o = null; } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var identifierBefore = GetReferences(tree, "G").Single(); Assert.Equal(tree, identifierBefore.Location.SourceTree); var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First(); var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);"); bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model); Assert.True(success); var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G"); Assert.Null(identifierAfter.Location.SourceTree); var info = model.GetSymbolInfo(identifierAfter); Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")] [WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")] public void GetForEachSymbolInfoWithOutVar() { var source = @"using System.Collections.Generic; public class C { void M() { foreach (var x in M2(out int i)) { } } IEnumerable<object> M2(out int j) { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachStatement); Assert.Equal("System.Object", info.ElementType.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); } [WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void DiscardAndArgList() { var text = @" using System; public class C { static void Main() { M(out _, __arglist(2, 3, true)); } static void M(out int x, __arglist) { x = 0; DumpArgs(new ArgIterator(__arglist)); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "23True"); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_01() { var text = @" public class C { static void Main() { M(1, __arglist(out int y)); M(2, __arglist(out var z)); System.Console.WriteLine(z); } static void M(int x, __arglist) { x = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(1, __arglist(out int y)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28), // (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32), // (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_02() { var text = @" public class C { static void Main() { __arglist(out int y); __arglist(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out int y); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23), // (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out int y); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9), // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // __arglist(out var z); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27), // (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out var z); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23), // (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out var z); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_01() { var text = @" public class C { static void M<T>() where T : new() { var x = new T(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z); Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)') Children(1): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_02() { var text = @" public class C { static void M<T>() where T : C, new() { var x = new T(out var z) {F1 = 1}; System.Console.WriteLine(z); } public int F1; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z) {F1 = 1}; Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z) {F1 = 1}", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}') Children(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1') Left: IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ConstructorBodyOperation() { var text = @" public class C { C() : this(out var x) { M(out var y); } => M(out var z); C (out int x){x=1;} void M (out int x){x=1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(out var x)", initializerSyntax.ToString()); compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree: @" IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation initializerOperation = model.GetOperation(initializerSyntax); Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind); Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent); Assert.Null(blockBodyOperation.Parent.Parent); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent); var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First(); Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);') Locals: Local_1: System.Int32 x Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Expression: IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MethodBodyOperation() { var text = @" public class C { int P { get {return M(out var x);} => M(out var y); } => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax); Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind); Assert.Null(expressionBodyOperation.Parent.Parent); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent); var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1); Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString()); Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900 var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);') BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyExpressionBodyOperation() { var text = @" public class C { int P => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", node3.ToString()); compilation.VerifyOperationTree(node3, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(node3).Parent); } [Fact] public void OutVarInConstructorUsedInObjectInitializer() { var source = @" public class C { public int Number { get; set; } public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { Number = i }; System.Console.WriteLine(c.Number); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] public void OutVarInConstructorUsedInCollectionInitializer() { var source = @" public class C : System.Collections.Generic.List<int> { public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { i, i, i }; System.Console.WriteLine(c[0]); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] [WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")] public void Issue49997() { var text = @" public class Cls { public static void Main() { if () .Test1().Test2(out var x1).Test3(); } } static class Ext { public static void Test3(this Cls x) {} } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last(); Assert.True(model.GetSymbolInfo(node).IsEmpty); } } internal static class OutVarTestsExtensions { internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self) { return (SingleVariableDesignationSyntax)self.Designation; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using static Roslyn.Test.Utilities.TestMetadata; using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.OutVar)] public class OutVarTests : CompilingTestBase { [Fact] public void OldVersion() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")] [WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")] public void DiagnosticsDifferenceBetweenLanguageVersions_01() { var text = @" public class Cls { public static void Test1() { Test(out int x1); } public static void Test2() { var x = new Cls(out int x2); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test(out int x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22), // (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33), // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_01() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_02() { var text = @" public class Cls { public static void Main() { Test1(out (var x1, var x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_03() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, long x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,28): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_04() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, (long x2, byte x3))); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,29): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29), // (6,38): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38), // (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,29): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29), // (6,38): error CS0165: Use of unassigned local variable 'x3' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_05() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2, x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_06() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; Test1(out var (x1)); System.Console.WriteLine(F1); } static ref int var(object x) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_07() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, x2: x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2: x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_08() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (ref x1, x2)); System.Console.WriteLine(F1); } static ref int var(ref object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (ref x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_09() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, (x2))); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_10() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var ((x1), x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var ((x1), x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_11() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_12() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out M1 (x1, x2)); System.Console.WriteLine(F1); } static ref int M1(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_13() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(ref var (x1, x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(ref int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(ref var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_14() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(var (x1, x2)); System.Console.WriteLine(F1); } static int var(object x1, object x2) { F1 = 123; return 124; } static object Test1(int x) { System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"124 123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_15() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out M1 (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int M1(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_16() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (a: x2, b: x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (a: x2, b: x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } 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; } internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == name); } private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name) { return GetDeclarations(tree, name).Single(); } internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name) { return GetOutVarDeclarations(tree, name).Single(); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name); } 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 IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration()); } [Fact] public void Simple_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); int x2; Test3(out x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references); } private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references); } internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode( SemanticModel model, DeclarationExpressionSyntax decl, IdentifierNameSyntax reference) { VerifyModelForOutVar( model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: reference); } private static void VerifyModelForOutVar( SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, bool isShadowed, bool verifyDataFlow = true, LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax); Assert.NotNull(symbol); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.False(((ILocalSymbol)symbol).IsFixed); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single(); if (isShadowed) { Assert.NotEqual(symbol, other); } else { Assert.Same(symbol, other); } Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type); 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, model.GetTypeInfo(reference).Type); } if (verifyDataFlow) { VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol); } } private static void AssertInfoForDeclarationExpressionSyntax( SemanticModel model, DeclarationExpressionSyntax decl, ISymbol expectedSymbol = null, ITypeSymbol expectedType = null ) { var symbolInfo = model.GetSymbolInfo(decl); Assert.Equal(expectedSymbol, symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl)); var typeInfo = model.GetTypeInfo(decl); Assert.Equal(expectedType, typeInfo.Type); // skip cases where operation is not supported AssertTypeFromOperation(model, expectedType, decl); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.Equal(expectedType, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl)); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.True(model.GetConversion(decl).IsIdentity); var typeSyntax = decl.Type; Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax)); Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax)); ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType(); if (expected?.IsErrorType() != false) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol); } typeInfo = model.GetTypeInfo(typeSyntax); Assert.Equal(expected, typeInfo.Type); Assert.Equal(expected, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax)); Assert.True(model.GetConversion(typeSyntax).IsIdentity); var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false); Assert.False(conversion.Exists); Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Null(model.GetDeclaredSymbol(decl)); } private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl) { // see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail // unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode. // what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from // error recovery mode var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault(); if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true) { // invalid syntax case where operation is not supported return; } Assert.Equal(expectedType, model.GetOperation(decl)?.Type); } private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol) { var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax; if (dataFlowParent == null) { if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax)) { Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent); } return; } if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); return; } var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (isExecutableCode) { Assert.True(dataFlow.Succeeded); Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); if (!isDelegateCreation) { Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); var flowsIn = FlowsIn(dataFlowParent, decl, references); Assert.Equal(flowsIn, dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(flowsIn, dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(FlowsOut(dataFlowParent, decl, references), dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(ReadOutside(dataFlowParent, references), dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(WrittenOutside(dataFlowParent, references), dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type); } private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; Assert.NotEqual(SymbolKind.Field, symbol.Kind); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; if (symbol.Kind == SymbolKind.Local) { var local = symbol.GetSymbol<SourceLocalSymbol>(); var parent = local.IdentifierToken.Parent; Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration())); if (parent.Kind() == SyntaxKind.VariableDeclarator) { var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent; switch (parent1.Kind()) { case SyntaxKind.FixedStatement: case SyntaxKind.ForStatement: case SyntaxKind.UsingStatement: break; default: Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind()); break; } } } Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl) { return (SingleVariableDesignationSyntax)decl.Designation; } private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart) { if (IsRead(reference)) { return true; } } } return false; } private static bool IsRead(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left != reference) { return true; } break; default: return true; } return false; } private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsRead(reference)) { return true; } } } return false; } private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { ForStatementSyntax forStatement; if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null && forStatement.Incrementors.Span.Contains(decl.Position) && forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null)) { return false; } var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault(); var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax); MethodDeclarationSyntax methodDeclParent; if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" && ((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null || methodDeclParent.Body.Statements.First() != containingReturnOrThrow)) { return false; } foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span) && (containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) && (reference.SpanStart > decl.SpanStart || (containingReturnOrThrow == null && reference.Ancestors().OfType<DoStatementSyntax>().Join( decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any()))) { if (IsRead(reference)) { return true; } } } return false; } private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsWrite(reference)) { return true; } } } return false; } private static bool IsWrite(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left == reference) { return true; } break; case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.PostDecrementExpression: return true; default: return false; } return false; } [Fact] public void Simple_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Int32 x1), x1); int x2 = 0; Test3(x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_03() { var text = @" public class Cls { public static void Main() { Test2(Test1(out (int, int) x1), x1); } static object Test1(out (int, int) x) { x = (123, 124); return null; } static void Test2(object x, (int, int) y) { System.Console.WriteLine(y); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_04() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1); } static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = new System.Collections.Generic.List<System.Int32>(); return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, out x1), x1); } static object Test1(out int x, out int y) { x = 123; y = 124; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, x1 = 124), x1); } static object Test1(out int x, int y) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_07() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1, x1 = 124); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y, int z) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_08() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), ref x1); int x2 = 0; Test3(ref x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, ref int y) { System.Console.WriteLine(y); } static void Test3(ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_09() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), out x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_10() { var text = @" public class Cls { public static void Main() { Test2(Test1(out dynamic x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_11() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int[] x1), x1); } static object Test1(out int[] x) { x = new [] {123}; return null; } static void Test2(object x, int[] y) { System.Console.WriteLine(y[0]); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_01() { var text = @" public class Cls { public static void Main() { int x1 = 0; Test1(out int x1); Test2(Test1(out int x2), out int x2); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS0128: A local variable named 'x1' is already defined in this scope // Test1(out int x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23), // (9,29): error CS0128: A local variable named 'x2' is already defined in this scope // out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13) ); } [Fact] public void Scope_02() { var text = @" public class Cls { public static void Main() { Test2(x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15) ); } [Fact] public void Scope_03() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_04() { var text = @" public class Cls { public static void Main() { Test1(out int x1); System.Console.WriteLine(x1); } static object Test1(out int x) { x = 1; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_05() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out var x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_Attribute_01() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_02() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_03() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_04() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void AttributeArgument_01() { var source = @" public class X { [Test(out var x3)] [Test(out int x4)] [Test(p: out var x5)] [Test(p: out int x6)] public static void Main() { } } class Test : System.Attribute { public Test(out int p) { p = 100; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (4,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out var x3)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11), // (4,19): error CS1003: Syntax error, ',' expected // [Test(out var x3)] Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19), // (5,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out int x4)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11), // (5,15): error CS1525: Invalid expression term 'int' // [Test(out int x4)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15), // (5,19): error CS1003: Syntax error, ',' expected // [Test(out int x4)] Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19), // (6,14): error CS1525: Invalid expression term 'out' // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14), // (6,14): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18), // (6,22): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22), // (7,14): error CS1525: Invalid expression term 'out' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14), // (7,14): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14), // (7,18): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18), // (7,18): error CS1525: Invalid expression term 'int' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22), // (4,15): error CS0103: The name 'var' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15), // (4,19): error CS0103: The name 'x3' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19), // (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out var x3)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6), // (5,19): error CS0103: The name 'x4' does not exist in the current context // [Test(out int x4)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19), // (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out int x4)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6), // (6,18): error CS0103: The name 'var' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18), // (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18), // (6,22): error CS0103: The name 'x5' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22), // (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6), // (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18), // (7,22): error CS0103: The name 'x6' does not exist in the current context // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22), // (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6) ); var tree = compilation.SyntaxTrees.Single(); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); Assert.False(GetOutVarDeclarations(tree, "x4").Any()); Assert.False(GetOutVarDeclarations(tree, "x5").Any()); Assert.False(GetOutVarDeclarations(tree, "x6").Any()); } [Fact] public void Scope_Catch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } } void Test4() { var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Scope_Catch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out int x1) && x1 > 0) { Dummy(x1); } } void Test4() { int x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out int x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out int x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out int x7) && x7 > 0) { int x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out int x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out int x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out int x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out int x10)) { int y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out int x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out int x14), TakeOutParam(out int x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out int x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out int x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out int x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out int x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out int x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Catch_01_ExplicitType() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Scope_ConstructorInitializers_01() { var source = @" public class X { public static void Main() { } X(byte x) : this(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : this(x4 && TakeOutParam(4, out int x4)) {} X(short x) : this(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : this(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : this(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : this(x7, 2) {} void Test73() { Dummy(x7, 3); } X(params object[] x) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : this(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : this(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_02() { var source = @" public class X : Y { public static void Main() { } X(byte x) : base(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : base(x4 && TakeOutParam(4, out int x4)) {} X(short x) : base(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : base(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : base(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : base(x7, 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } public class Y { public Y(params object[] x) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : base(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : base(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_03() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D { public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_04() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D : C { public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_05() { var source = @"using System; class D { public D(int o) : this(SpeculateHere) { } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_06() { var source = @"using System; class D : C { public D(int o) : base(SpeculateHere) { } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var initializerOperation = model.GetOperation(initializer); Assert.Null(initializerOperation.Parent.Parent.Parent); VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Expression: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)') Children(1): IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5') IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5') Left: IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o') IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5') Left: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] public void Scope_ConstructorInitializers_07() { var source = @" public class X : Y { public static void Main() { } X(byte x3) : base(TakeOutParam(3, out var x3)) {} X(sbyte x) : base(TakeOutParam(4, out var x4)) { int x4 = 1; System.Console.WriteLine(x4); } X(ushort x) : base(TakeOutParam(51, out var x5)) => Dummy(TakeOutParam(52, out var x5), x5); X(short x) : base(out int x6, x6) {} X(uint x) : base(out var x7, x7) {} X(int x) : base(TakeOutParam(out int x8, x8)) {} X(ulong x) : base(TakeOutParam(out var x9, x9)) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } public class Y { public Y(params object[] x) {} public Y(out int x, int y) { x = y; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : base(TakeOutParam(3, out var x3)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40), // (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x4 = 1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13), // (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // => Dummy(TakeOutParam(52, out var x5), x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39), // (24,28): error CS0165: Use of unassigned local variable 'x6' // : base(out int x6, x6) Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28), // (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list. // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28), // (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20), // (32,41): error CS0165: Use of unassigned local variable 'x8' // : base(TakeOutParam(out int x8, x8)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41), // (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list. // : base(TakeOutParam(out var x9, x9)) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").Single(); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref); } [Fact] public void Scope_Do_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { do { Dummy(x1); } while (TakeOutParam(true, out var x1) && x1); } void Test2() { do Dummy(x2); while (TakeOutParam(true, out var x2) && x2); } void Test4() { var x4 = 11; Dummy(x4); do Dummy(x4); while (TakeOutParam(true, out var x4) && x4); } void Test6() { do Dummy(x6); while (x6 && TakeOutParam(true, out var x6)); } void Test7() { do { var x7 = 12; Dummy(x7); } while (TakeOutParam(true, out var x7) && x7); } void Test8() { do Dummy(x8); while (TakeOutParam(true, out var x8) && x8); System.Console.WriteLine(x8); } void Test9() { do { Dummy(x9); do Dummy(x9); while (TakeOutParam(true, out var x9) && x9); // 2 } while (TakeOutParam(true, out var x9) && x9); } void Test10() { do { var y10 = 12; Dummy(y10); } while (TakeOutParam(y10, out var x10)); } //void Test11() //{ // do // { // let y11 = 12; // Dummy(y11); // } // while (TakeOutParam(y11, out var x11)); //} void Test12() { do var y12 = 12; while (TakeOutParam(y12, out var x12)); } //void Test13() //{ // do // let y13 = 12; // while (TakeOutParam(y13, out var x13)); //} void Test14() { do { Dummy(x14); } while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13), // (14,19): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19), // (22,19): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19), // (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43), // (32,19): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy(x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19), // (40,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16), // (39,19): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19), // (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17), // (56,19): error CS0841: Cannot use local variable 'x8' before it is declared // Dummy(x8); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19), // (59,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34), // (66,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19), // (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9); // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47), // (68,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23), // (81,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29), // (98,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29), // (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17), // (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46), // (112,19): error CS0841: Cannot use local variable 'x14' before it is declared // Dummy(x14); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[1]); VerifyNotAnOutLocal(model, x7Ref[0]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[1]); VerifyNotAnOutLocal(model, y10Ref[0]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Do_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) do { } while (TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Do_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@" do {} while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { int f = 1; do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false); if (f) { do ; while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { } bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0; bool Test4(object o) => x4 && TakeOutParam(o, out int x4); bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0; void Test72() => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test11(object x11) => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,29): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4(object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29), // (13,67): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67), // (19,28): error CS0103: The name 'x7' does not exist in the current context // void Test72() => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool Test11(object x11) => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")] public void Scope_ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test3() { bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0; f(null); } void Test4() { bool f (object o) => x4 && TakeOutParam(o, out int x4); f(null); } void Test5() { bool f (object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; f(null, null); } void Test6() { bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0; f1(null); f2(null); } void Test7() { Dummy(x7, 1); bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0; Dummy(x7, 2); f(null); } void Test11() { var x11 = 11; Dummy(x11); bool f (object o) => TakeOutParam(o, out int x11) && x11 > 0; f(null); } void Test12() { bool f (object o) => TakeOutParam(o, out int x12) && x12 > 0; var x12 = 11; Dummy(x12); f(null); } System.Action Test13() { return () => { bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0; f(null); }; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15), // (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54), // (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); // Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214 var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").Single(); VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref); } [Fact] public void ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out int x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedLocalFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out var x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void Scope_ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { } bool Test3 => TakeOutParam(3, out int x3) && x3 > 0; bool Test4 => x4 && TakeOutParam(4, out int x4); bool Test5 => TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0; bool Test71 => TakeOutParam(7, out int x7) && x7 > 0; bool Test72 => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool this[object x11] => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,19): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 => x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19), // (13,44): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44), // (19,26): error CS0103: The name 'x7' does not exist in the current context // bool Test72 => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool this[object x11] => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void ExpressionBodiedProperties_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void Scope_ExpressionStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { Dummy(TakeOutParam(true, out var x1), x1); { Dummy(TakeOutParam(true, out var x1), x1); } Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ExpressionStatement_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) Test2(Test1(out int x1), x1); if (test) { Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_ExpressionStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ExpressionStatement_04() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Scope_FieldInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 = x4 && TakeOutParam(4, out int x4); bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,57): error CS0103: The name 'x8' does not exist in the current context // bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57), // (23,19): error CS0103: The name 'x9' does not exist in the current context // bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReference(tree, "x8"); VerifyModelForOutVar(model, x8Decl); VerifyNotInScope(model, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReference(tree, "x9"); VerifyNotInScope(model, x9Ref); VerifyModelForOutVar(model, x9Decl); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_FieldInitializers_02() { var source = @"using static Test; public enum X { Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0, Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Test72 = x7, } class Test { public static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'x4' before it is declared // Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13), // (9,38): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38), // (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant // Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13), // (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14), // (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70), // (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant // Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14), // (15,14): error CS0103: The name 'x7' does not exist in the current context // Test72 = x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14), // (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant // Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0') Locals: Local_1: System.Int32 x3 IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0') Condition: IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_FieldInitializers_03() { var source = @" public class X { public static void Main() { } const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; const bool Test4 = x4 && TakeOutParam(4, out int x4); const bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; const bool Test72 = x7 > 2; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant // const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24), // (10,24): error CS0841: Cannot use local variable 'x4' before it is declared // const bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24), // (13,49): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49), // (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant // const bool Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("X.Test5").WithLocation(12, 24), // (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25), // (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73), // (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant // const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25), // (19,25): error CS0103: The name 'x7' does not exist in the current context // const bool Test72 = x7 > 2; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_FieldInitializers_04() { var source = @" class X : Y { public static void Main() { } bool Test3 = TakeOutParam(out int x3, x3); bool Test4 = TakeOutParam(out var x4, x4); bool Test5 = TakeOutParam(out int x5, 5); X() : this(x5) { System.Console.WriteLine(x5); } X(object x) : base(x5) => System.Console.WriteLine(x5); static bool Test6 = TakeOutParam(out int x6, 6); static X() { System.Console.WriteLine(x6); } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } class Y { public Y(object y) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,43): error CS0165: Use of unassigned local variable 'x3' // bool Test3 = TakeOutParam(out int x3, x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43), // (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list. // bool Test4 = TakeOutParam(out var x4, x4); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43), // (15,12): error CS0103: The name 'x5' does not exist in the current context // : this(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12), // (17,34): error CS0103: The name 'x5' does not exist in the current context // System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34), // (21,12): error CS0103: The name 'x5' does not exist in the current context // : base(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12), // (22,33): error CS0103: The name 'x5' does not exist in the current context // => System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33), // (27,34): error CS0103: The name 'x6' does not exist in the current context // System.Console.WriteLine(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(4, x5Ref.Length); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); VerifyNotInScope(model, x5Ref[3]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void FieldInitializers_05() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,54): error CS0165: Use of unassigned local variable 'x1' // bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void FieldInitializers_06() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void Scope_Fixed_01() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p = Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // fixed (int* p = Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { fixed (int* p = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Fixed_02() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* x1 = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2), x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p = Dummy(TakeOutParam(true, out var x3) && x3)) { Dummy(x3); } } void Test4() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4), p2 = Dummy(TakeOutParam(true, out var x4) && x4)) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (14,66): error CS0165: Use of unassigned local variable 'x1' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2 = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Fixed_02() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Scope_For_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for ( Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (; Dummy(TakeOutParam(true, out var x1) && x1) ;) { Dummy(x1); } } void Test2() { for (; Dummy(TakeOutParam(true, out var x2) && x2) ;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (; Dummy(TakeOutParam(true, out var x4) && x4) ;) Dummy(x4); } void Test6() { for (; Dummy(x6 && TakeOutParam(true, out var x6)) ;) Dummy(x6); } void Test7() { for (; Dummy(TakeOutParam(true, out var x7) && x7) ;) { var x7 = 12; Dummy(x7); } } void Test8() { for (; Dummy(TakeOutParam(true, out var x8) && x8) ;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (; Dummy(TakeOutParam(true, out var x9) && x9) ;) { Dummy(x9); for (; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;) Dummy(x9); } } void Test10() { for (; Dummy(TakeOutParam(y10, out var x10)) ;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (; // Dummy(TakeOutParam(y11, out var x11)) // ;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (; Dummy(TakeOutParam(y12, out var x12)) ;) var y12 = 12; } //void Test13() //{ // for (; // Dummy(TakeOutParam(y13, out var x13)) // ;) // let y13 = 12; //} void Test14() { for (; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_03() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(TakeOutParam(true, out var x1) && x1) ) { Dummy(x1); } } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2) ) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (;; Dummy(TakeOutParam(true, out var x4) && x4) ) Dummy(x4); } void Test6() { for (;; Dummy(x6 && TakeOutParam(true, out var x6)) ) Dummy(x6); } void Test7() { for (;; Dummy(TakeOutParam(true, out var x7) && x7) ) { var x7 = 12; Dummy(x7); } } void Test8() { for (;; Dummy(TakeOutParam(true, out var x8) && x8) ) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (;; Dummy(TakeOutParam(true, out var x9) && x9) ) { Dummy(x9); for (;; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ) Dummy(x9); } } void Test10() { for (;; Dummy(TakeOutParam(y10, out var x10)) ) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (;; // Dummy(TakeOutParam(y11, out var x11)) // ) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (;; Dummy(TakeOutParam(y12, out var x12)) ) var y12 = 12; } //void Test13() //{ // for (;; // Dummy(TakeOutParam(y13, out var x13)) // ) // let y13 = 12; //} void Test14() { for (;; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (16,19): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19), // (25,19): error CS0103: The name 'x2' does not exist in the current context // Dummy(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (44,19): error CS0103: The name 'x6' does not exist in the current context // Dummy(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19), // (63,19): error CS0103: The name 'x8' does not exist in the current context // Dummy(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (74,19): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19), // (78,23): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23), // (71,14): warning CS0162: Unreachable code detected // Dummy(TakeOutParam(true, out var x9) && x9) Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44), // (128,19): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref[0]); VerifyNotInScope(model, x2Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref[0]); VerifyNotInScope(model, x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0]); VerifyNotInScope(model, x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyNotInScope(model, x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyNotInScope(model, x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); VerifyNotInScope(model, x14Ref[1]); } [Fact] public void Scope_For_04() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (var b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (var b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (var b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (var b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (var b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (var b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (var b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (var b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (var b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (var b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (var b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (var b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_05() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (bool b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (bool b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (bool b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (bool b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (bool b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (bool b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (bool b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_06() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var x1 = Dummy(TakeOutParam(true, out var x1) && x1) ;;) {} } void Test2() { for (var x2 = true; Dummy(TakeOutParam(true, out var x2) && x2) ;) {} } void Test3() { for (var x3 = true;; Dummy(TakeOutParam(true, out var x3) && x3) ) {} } void Test4() { for (bool x4 = Dummy(TakeOutParam(true, out var x4) && x4) ;;) {} } void Test5() { for (bool x5 = true; Dummy(TakeOutParam(true, out var x5) && x5) ;) {} } void Test6() { for (bool x6 = true;; Dummy(TakeOutParam(true, out var x6) && x6) ) {} } void Test7() { for (bool x7 = true, b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) {} } void Test8() { for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8), b2 = Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2 = Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } void Test10() { for (var b = x10; Dummy(TakeOutParam(true, out var x10) && x10) && Dummy(TakeOutParam(true, out var x10) && x10); Dummy(TakeOutParam(true, out var x10) && x10)) {} } void Test11() { for (bool b = x11; Dummy(TakeOutParam(true, out var x11) && x11) && Dummy(TakeOutParam(true, out var x11) && x11); Dummy(TakeOutParam(true, out var x11) && x11)) {} } void Test12() { for (Dummy(x12); Dummy(x12) && Dummy(TakeOutParam(true, out var x12) && x12); Dummy(TakeOutParam(true, out var x12) && x12)) {} } void Test13() { for (var b = x13; Dummy(x13); Dummy(TakeOutParam(true, out var x13) && x13), Dummy(TakeOutParam(true, out var x13) && x13)) {} } void Test14() { for (bool b = x14; Dummy(x14); Dummy(TakeOutParam(true, out var x14) && x14), Dummy(TakeOutParam(true, out var x14) && x14)) {} } void Test15() { for (Dummy(x15); Dummy(x15); Dummy(x15), Dummy(TakeOutParam(true, out var x15) && x15)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47), // (13,54): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54), // (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x2) && x2) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47), // (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used // for (var x2 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3) && x3) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used // for (var x3 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18), // (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47), // (37,54): error CS0165: Use of unassigned local variable 'x4' // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54), // (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x5) && x5) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47), // (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used // for (bool x5 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19), // (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x6) && x6) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47), // (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used // for (bool x6 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19), // (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47), // (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2 = Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52), // (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47), // (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47), // (77,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23), // (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47), // (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47), // (86,22): error CS0103: The name 'x10' does not exist in the current context // for (var b = x10; Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22), // (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope // Dummy(TakeOutParam(true, out var x10) && x10); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47), // (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x10) && x10)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47), // (95,23): error CS0103: The name 'x11' does not exist in the current context // for (bool b = x11; Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23), // (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope // Dummy(TakeOutParam(true, out var x11) && x11); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47), // (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x11) && x11)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47), // (104,20): error CS0103: The name 'x12' does not exist in the current context // for (Dummy(x12); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20), // (105,20): error CS0841: Cannot use local variable 'x12' before it is declared // Dummy(x12) && Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20), // (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x12) && x12)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47), // (113,22): error CS0103: The name 'x13' does not exist in the current context // for (var b = x13; Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22), // (114,20): error CS0103: The name 'x13' does not exist in the current context // Dummy(x13); Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20), // (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope // Dummy(TakeOutParam(true, out var x13) && x13)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47), // (122,23): error CS0103: The name 'x14' does not exist in the current context // for (bool b = x14; Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23), // (123,20): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20), // (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope // Dummy(TakeOutParam(true, out var x14) && x14)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47), // (131,20): error CS0103: The name 'x15' does not exist in the current context // for (Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20), // (132,20): error CS0103: The name 'x15' does not exist in the current context // Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20), // (133,20): error CS0841: Cannot use local variable 'x15' before it is declared // Dummy(x15), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(3, x10Decl.Length); Assert.Equal(4, x10Ref.Length); VerifyNotInScope(model, x10Ref[0]); VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]); VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]); var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Decl.Length); Assert.Equal(4, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]); VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]); var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Decl.Length); Assert.Equal(4, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]); VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(4, x13Ref.Length); VerifyNotInScope(model, x13Ref[0]); VerifyNotInScope(model, x13Ref[1]); VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyNotInScope(model, x14Ref[0]); VerifyNotInScope(model, x14Ref[1]); VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(4, x15Ref.Length); VerifyNotInScope(model, x15Ref[0]); VerifyNotInScope(model, x15Ref[1]); VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]); } [Fact] public void Scope_For_07() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(x1), Dummy(TakeOutParam(true, out var x1) && x1)) {} } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2), Dummy(TakeOutParam(true, out var x2) && x2)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,20): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20), // (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2) && x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_06() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1))) { x0++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"20 30 -- 20 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_07() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 -- 10 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Foreach_01() { var source = @" public class X { public static void Main() { } System.Collections.IEnumerable Dummy(params object[] x) {return null;} void Test1() { foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } void Test15() { foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60), // (35,33): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65), // (68,46): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46), // (86,46): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,57): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57), // (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_If_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (TakeOutParam(true, out var x1)) { Dummy(x1); } else { System.Console.WriteLine(x1); } } void Test2() { if (TakeOutParam(true, out var x2)) Dummy(x2); else System.Console.WriteLine(x2); } void Test3() { if (TakeOutParam(true, out var x3)) Dummy(x3); else { var x3 = 12; System.Console.WriteLine(x3); } } void Test4() { var x4 = 11; Dummy(x4); if (TakeOutParam(true, out var x4)) Dummy(x4); } void Test5(int x5) { if (TakeOutParam(true, out var x5)) Dummy(x5); } void Test6() { if (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { if (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { if (TakeOutParam(true, out var x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { if (TakeOutParam(true, out var x9)) { Dummy(x9); if (TakeOutParam(true, out var x9)) // 2 Dummy(x9); } } void Test10() { if (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } void Test12() { if (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // if (TakeOutParam(y13, out var x13)) // let y13 = 12; //} static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13), // (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x3 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17), // (46,40): error CS0128: A local variable named 'x4' is already defined in this scope // if (TakeOutParam(true, out var x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40), // (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x5)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40), // (58,13): error CS0841: Cannot use local variable 'x6' before it is declared // if (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13), // (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17), // (83,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19), // (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44), // (91,26): error CS0103: The name 'y10' does not exist in the current context // if (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26), // (100,26): error CS0103: The name 'y12' does not exist in the current context // if (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26), // (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); } [Fact] public void Scope_If_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) if (TakeOutParam(true, out var x1)) { } else { } x1++; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_If_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@" if (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, TakeOutParam(val, out var x1), x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) ; if (f) { if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_Lambda_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} System.Action<object> Test1() { return (o) => let x1 = o; } System.Action<object> Test2() { return (o) => let var x2 = o; } void Test3() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0)); } void Test4() { Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); } void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0)); } void Test6() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0)); } void Test7() { Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0), x7); Dummy(x7, 2); } void Test8() { Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8)); } void Test9() { Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && x9 > 0), x9); } void Test10() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && x10 > 0), TakeOutParam(true, out var x10), x10); } void Test11() { var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && x11 > 0), x11); } void Test12() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73), // (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73), // (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73), // (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { var d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { var d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // var d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // var d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); object d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { object d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { object d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { object d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,53): error CS0128: A local variable named 'x4' is already defined in this scope // object d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53), // (24,26): error CS0841: Cannot use local variable 'x6' before it is declared // object d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26), // (36,50): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var x1 = Dummy(TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { object x2 = Dummy(TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] public void Scope_LocalDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Scope_LocalDeclarationStmt_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y1 = Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] public void Scope_LocalDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d =TakeOutParam(true, out var x1) && x1 != null; x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (d, dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var (d, dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { var (d, dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var (d, dd, ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,51): error CS0128: A local variable named 'x4' is already defined in this scope // var (d, dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51), // (24,24): error CS0841: Cannot use local variable 'x6' before it is declared // var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); (object d, object dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { (object d, object dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { (object d, object dd, object ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,61): error CS0128: A local variable named 'x4' is already defined in this scope // (object d, object dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61), // (24,34): error CS0841: Cannot use local variable 'x6' before it is declared // (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (x1, dd) = (TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { (object x2, object dd) = (TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Dummy(x1)); Dummy(x1); } void Test2() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2), Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3), Dummy(x3)); } void Test4() { (object d1, object d2) = (Dummy(x4), Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,67): error CS0128: A local variable named 'x1' is already defined in this scope // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67), // (12,72): error CS0165: Use of unassigned local variable 'x1' // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,41): error CS0841: Cannot use local variable 'x4' before it is declared // (object d1, object d2) = (Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyNotAnOutLocal(model, x1Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_05() { var source = @" public class X { public static void Main() { } void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" var (y1, dd) = (TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var (d, dd) = (TakeOutParam(true, out var x1), x1); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] public void Scope_Lock_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { lock (Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { lock (Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Dummy(x4); } void Test6() { lock (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { lock (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { lock (Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { lock (Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { lock (Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // lock (Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { lock (Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // lock (Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { lock (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,48): error CS0128: A local variable named 'x4' is already defined in this scope // lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48), // (35,21): error CS0841: Cannot use local variable 'x6' before it is declared // lock (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (60,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19), // (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52), // (68,34): error CS0103: The name 'y10' does not exist in the current context // lock (Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34), // (86,34): error CS0103: The name 'y12' does not exist in the current context // lock (Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,45): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Lock_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { if (true) lock (Dummy(TakeOutParam(true, out var x1))) { } x1++; } static object TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (17,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Lock_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@" lock (Dummy(TakeOutParam(true, out var x1), x1)) ; "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(TakeOutParam(""lock"", out var x1), x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_ParameterDefault_01() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out int x4)) {} void Test5(bool p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0') Locals: Local_1: System.Int32 x3 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0') Left: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_ParameterDefault_02() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out var x4)) {} void Test5(bool p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out var x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_PropertyInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); bool Test5 {get;} = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 {get;} = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,25): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,32): error CS0103: The name 'x7' does not exist in the current context // bool Test72 {get;} = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_03() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,63): error CS0165: Use of unassigned local variable 'x1' // bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void PropertyInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(new X().Test1); } int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Scope_Query_01() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); } void Test2() { var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); } void Test3() { var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); } void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } void Test6() { var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); } void Test7() { var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); } void Test8() { var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); } void Test9() { var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); } void Test10() { var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; } void Test11() { var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,26): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26), // (27,15): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15), // (35,32): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32), // (37,15): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15), // (45,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35), // (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35), // (49,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32), // (49,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36), // (52,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15), // (53,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15), // (61,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35), // (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35), // (66,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32), // (66,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36), // (69,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15), // (70,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15), // (78,26): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26), // (80,15): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15), // (87,27): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27), // (89,27): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27), // (91,26): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26), // (91,31): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31), // (93,15): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15), // (94,15): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15), // (102,15): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15), // (112,25): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25), // (109,25): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25), // (114,15): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15), // (115,15): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15), // (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24), // (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } [Fact] public void Scope_Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35), // (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35), // (22,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32), // (22,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36), // (25,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15), // (26,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15), // (35,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35), // (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35), // (40,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32), // (40,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36), // (43,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15), // (44,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0; var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0); Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62), // (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51), // (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58), // (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49), // (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51), // (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51), // (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47), // (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49), // (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54), // (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(3, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVarDuplicateInSameScope(model, yDecl); VerifyNotAnOutLocal(model, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); break; } VerifyNotAnOutLocal(model, yRef[2]); switch (i) { case 12: VerifyNotAnOutLocal(model, yRef[1]); break; default: VerifyNotAnOutLocal(model, yRef[1]); break; } } var y13Decl = GetOutVarDeclarations(tree, "y13").Single(); var y13Ref = GetReference(tree, "y13"); VerifyModelForOutVar(model, y13Decl, y13Ref); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_06() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y1), TakeOutParam(out int y2), TakeOutParam(out int y3), TakeOutParam(out int y4), TakeOutParam(out int y5), TakeOutParam(out int y6), TakeOutParam(out int y7), TakeOutParam(out int y8), TakeOutParam(out int y9), TakeOutParam(out int y10), TakeOutParam(out int y11), TakeOutParam(out int y12), from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62), // (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51), // (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58), // (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49), // (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51), // (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51), // (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47), // (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49), // (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54), // (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); break; case 12: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; default: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; } } } [Fact] public void Scope_Query_07() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y3), from x1 in new[] { 0 } select x1 into x1 join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on x1 equals x3 select y3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,62): error CS0128: A local variable named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); const string id = "y3"; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); // Since the name is declared twice in the same scope, // both references are to the same declaration. VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); } [Fact] public void Scope_Query_08() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4) ) ? 1 : 0} from y1 in new[] { 1 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by x1 into y4 select y4; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // from y1 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24), // (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24), // (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23), // (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 5; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_09() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by 1 into y4 select y4 == null ? 1 : 0 into x2 join y5 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4), TakeOutParam(out var y5) ) ? 1 : 0 } on x2 equals y5 select x2; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // var res = from y1 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24), // (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24), // (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23), // (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24), // (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5' // join y5 in new[] { Dummy(TakeOutParam(out var y1), Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 6; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); switch (i) { case 4: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; case 5: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; default: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; } } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] [WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")] public void Scope_Query_10() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } select y1; } void Test2() { var res = from y2 in new[] { 0 } join x3 in new[] { 1 } on TakeOutParam(out var y2) ? y2 : 0 equals x3 select y2; } void Test3() { var res = from x3 in new[] { 0 } join y3 in new[] { 1 } on x3 equals TakeOutParam(out var y3) ? y3 : 0 select y3; } void Test4() { var res = from y4 in new[] { 0 } where TakeOutParam(out var y4) && y4 == 1 select y4; } void Test5() { var res = from y5 in new[] { 0 } orderby TakeOutParam(out var y5) && y5 > 1, 1 select y5; } void Test6() { var res = from y6 in new[] { 0 } orderby 1, TakeOutParam(out var y6) && y6 > 1 select y6; } void Test7() { var res = from y7 in new[] { 0 } group TakeOutParam(out var y7) && y7 == 3 by y7; } void Test8() { var res = from y8 in new[] { 0 } group y8 by TakeOutParam(out var y8) && y8 == 3; } void Test9() { var res = from y9 in new[] { 0 } let x4 = TakeOutParam(out var y9) && y9 > 0 select y9; } void Test10() { var res = from y10 in new[] { 0 } select TakeOutParam(out var y10) && y10 > 0; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052 compilation.VerifyDiagnostics( // (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59), // (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(out var y2) ? y2 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48), // (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(out var y3) ? y3 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52), // (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(out var y4) && y4 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46), // (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(out var y5) && y5 > 1, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48), // (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(out var y6) && y6 > 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48), // (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(out var y7) && y7 == 3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46), // (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(out var y8) && y8 == 3; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43), // (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x4 = TakeOutParam(out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49), // (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(out var y10) && y10 > 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 11; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(i == 10 ? 1 : 2, yRef.Length); switch (i) { case 4: case 6: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; case 8: VerifyModelForOutVar(model, yDecl, yRef[1]); VerifyNotAnOutLocal(model, yRef[0]); break; case 10: VerifyModelForOutVar(model, yDecl, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; } } } [Fact] public void Scope_Query_11() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y1), from x2 in new [] { y1 } where TakeOutParam(x1, out var y1) select x2) select x1; } void Test2() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y2), TakeOutParam(x1 + 1, out var y2)) select x1; } void Test3() { var res = from x1 in new [] { 1 } where TakeOutParam(out int y3, y3) select x1; } void Test4() { var res = from x1 in new [] { 1 } where TakeOutParam(out var y4, y4) select x1; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x, int y) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(x1, out var y1) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62), // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray(); var y1Ref = GetReferences(tree, "y1").Single(); Assert.Equal(2, y1Decl.Length); VerifyModelForOutVar(model, y1Decl[0], y1Ref); VerifyModelForOutVar(model, y1Decl[1]); var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray(); Assert.Equal(2, y2Decl.Length); VerifyModelForOutVar(model, y2Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").Single(); VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").Single(); VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0} join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0} on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0 equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0 where TakeOutParam(6, out var y6) && Print(y6) orderby TakeOutParam(7, out var y7) && Print(y7), TakeOutParam(8, out var y8) && Print(y8) group TakeOutParam(9, out var y9) && Print(y9) by TakeOutParam(10, out var y10) && Print(y10) into g let x11 = TakeOutParam(11, out var y11) && Print(y11) select TakeOutParam(12, out var y12) && Print(y12); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl, yRef); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString()); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutVar(model, yDecl, yRef); } [Fact] public void Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in new[] { true } select a && TakeOutParam(3, out int x1) || x1 > 0; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,62): error CS0165: Use of unassigned local variable 'x1' // select a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); compilation.VerifyOperationTree(x1Decl, expectedOperationTree: @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') "); } [Fact] public void Query_04() { var source = @" using System.Linq; public class X { public static void Main() { System.Console.WriteLine(Test1()); } static int Test1() { var res = from a in new[] { 1 } select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; return res.Single(); } static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in (new[] { 1 }).AsQueryable() select TakeOutParam(a, out int x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,46): error CS8198: An expression tree may not contain an out argument variable declaration. // select TakeOutParam(a, out int x1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46) ); } [Fact] public void Scope_ReturnStatement_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) { return null; } object Test1() { return Dummy(TakeOutParam(true, out var x1), x1); { return Dummy(TakeOutParam(true, out var x1), x1); } return Dummy(TakeOutParam(true, out var x1), x1); } object Test2() { return Dummy(x2, TakeOutParam(true, out var x2)); } object Test3(int x3) { return Dummy(TakeOutParam(true, out var x3), x3); } object Test4() { var x4 = 11; Dummy(x4); return Dummy(TakeOutParam(true, out var x4), x4); } object Test5() { return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //object Test6() //{ // let x6 = 11; // Dummy(x6); // return Dummy(TakeOutParam(true, out var x6), x6); //} //object Test7() //{ // return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} object Test8() { return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } object Test9(bool y9) { if (y9) return Dummy(TakeOutParam(true, out var x9), x9); return null; } System.Func<object> Test10(bool y10) { return () => { if (y10) return Dummy(TakeOutParam(true, out var x10), x10); return null;}; } object Test11() { Dummy(x11); return Dummy(TakeOutParam(true, out var x11), x11); } object Test12() { return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53), // (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49), // (14,13): warning CS0162: Unreachable code detected // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13), // (21,22): error CS0841: Cannot use local variable 'x2' before it is declared // return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22), // (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49), // (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope // return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ReturnStatement_02() { var source = @" public class X { public static void Main() { } int Dummy(params object[] x) { return 0;} int Test1(bool val) { if (val) return Dummy(TakeOutParam(true, out var x1)); x1++; return 0; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ReturnStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@" return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(TakeOutParam(""return"", out var x1), x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static object Test(bool val) { if (val) return Dummy(TakeOutParam(""return 1"", out var x2), x2); if (!val) { return Dummy(TakeOutParam(""return 2"", out var x2), x2); } return null; } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return 1 return 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Switch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { switch (TakeOutParam(1, out var x1) ? x1 : 0) { case 0: Dummy(x1, 0); break; } Dummy(x1, 1); } void Test4() { var x4 = 11; Dummy(x4); switch (TakeOutParam(4, out var x4) ? x4 : 0) { case 4: Dummy(x4); break; } } void Test5(int x5) { switch (TakeOutParam(5, out var x5) ? x5 : 0) { case 5: Dummy(x5); break; } } void Test6() { switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) { case 6: Dummy(x6); break; } } void Test7() { switch (TakeOutParam(7, out var x7) ? x7 : 0) { case 7: var x7 = 12; Dummy(x7); break; } } void Test9() { switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 0); switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 1); break; } break; } } void Test10() { switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) { case 10: var y10 = 12; Dummy(y10); break; } } //void Test11() //{ // switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0)) // { // case 11: // let y11 = 12; // Dummy(y11); // break; // } //} void Test14() { switch (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ? 1 : 0) { case 0: Dummy(x14); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (27,41): error CS0128: A local variable named 'x4' is already defined in this scope // switch (TakeOutParam(4, out var x4) ? x4 : 0) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41), // (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(5, out var x5) ? x5 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41), // (47,17): error CS0841: Cannot use local variable 'x6' before it is declared // switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17), // (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21), // (71,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9, 0); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23), // (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(9, out var x9) ? x9 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49), // (85,17): error CS0103: The name 'y10' does not exist in the current context // switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17), // (108,43): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Switch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) switch (TakeOutParam(1, out var x1) ? 1 : 0) { case 0: break; } Dummy(x1, 1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,15): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Switch_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@" switch (Dummy(TakeOutParam(true, out var x1), x1)) {} "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1))) { case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_SwitchLabelGuard_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test1(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 1 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 2 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; } } void Test2(int val) { switch (val) { case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Dummy(x2); break; } } void Test3(int x3, int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x3), x3): Dummy(x3); break; } } void Test4(int val) { var x4 = 11; switch (val) { case 0 when Dummy(TakeOutParam(true, out var x4), x4): Dummy(x4); break; case 1 when Dummy(x4): Dummy(x4); break; } } void Test5(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x5), x5): Dummy(x5); break; } var x5 = 11; Dummy(x5); } //void Test6(int val) //{ // let x6 = 11; // switch (val) // { // case 0 when Dummy(x6): // Dummy(x6); // break; // case 1 when Dummy(TakeOutParam(true, out var x6), x6): // Dummy(x6); // break; // } //} //void Test7(int val) //{ // switch (val) // { // case 0 when Dummy(TakeOutParam(true, out var x7), x7): // Dummy(x7); // break; // } // let x7 = 11; // Dummy(x7); //} void Test8(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test9(int val) { switch (val) { case 0 when Dummy(x9): int x9 = 9; Dummy(x9); break; case 2 when Dummy(x9 = 9): Dummy(x9); break; case 1 when Dummy(TakeOutParam(true, out var x9), x9): Dummy(x9); break; } } //void Test10(int val) //{ // switch (val) // { // case 1 when Dummy(TakeOutParam(true, out var x10), x10): // Dummy(x10); // break; // case 0 when Dummy(x10): // let x10 = 10; // Dummy(x10); // break; // case 2 when Dummy(x10 = 10, x10): // Dummy(x10); // break; // } //} void Test11(int val) { switch (x11 ? val : 0) { case 0 when Dummy(x11): Dummy(x11, 0); break; case 1 when Dummy(TakeOutParam(true, out var x11), x11): Dummy(x11, 1); break; } } void Test12(int val) { switch (x12 ? val : 0) { case 0 when Dummy(TakeOutParam(true, out var x12), x12): Dummy(x12, 0); break; case 1 when Dummy(x12): Dummy(x12, 1); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case 1 when Dummy(TakeOutParam(true, out var x13), x13): Dummy(x13); break; } } void Test14(int val) { switch (val) { case 1 when Dummy(TakeOutParam(true, out var x14), x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test15(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x15), x15): case 1 when Dummy(TakeOutParam(true, out var x15), x15): Dummy(x15); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (30,31): error CS0841: Cannot use local variable 'x2' before it is declared // case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31), // (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x3), x3): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58), // (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x4), x4): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58), // (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x5), x5): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58), // (102,95): error CS0128: A local variable named 'x8' is already defined in this scope // case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95), // (112,31): error CS0841: Cannot use local variable 'x9' before it is declared // case 0 when Dummy(x9): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31), // (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x9), x9): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58), // (144,17): error CS0103: The name 'x11' does not exist in the current context // switch (x11 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17), // (146,31): error CS0103: The name 'x11' does not exist in the current context // case 0 when Dummy(x11): Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31), // (147,23): error CS0103: The name 'x11' does not exist in the current context // Dummy(x11, 0); Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23), // (157,17): error CS0103: The name 'x12' does not exist in the current context // switch (x12 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17), // (162,31): error CS0103: The name 'x12' does not exist in the current context // case 1 when Dummy(x12): Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31), // (163,23): error CS0103: The name 'x12' does not exist in the current context // Dummy(x12, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23), // (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x13), x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58), // (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x14), x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58), // (198,58): error CS0128: A local variable named 'x15' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58), // (198,64): error CS0165: Use of unassigned local variable 'x15' // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(6, x1Ref.Length); for (int i = 0; i < x1Decl.Length; i++) { VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]); } var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(4, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyNotAnOutLocal(model, x4Ref[3]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]); VerifyNotAnOutLocal(model, x5Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(6, x9Ref.Length); VerifyNotAnOutLocal(model, x9Ref[0]); VerifyNotAnOutLocal(model, x9Ref[1]); VerifyNotAnOutLocal(model, x9Ref[2]); VerifyNotAnOutLocal(model, x9Ref[3]); VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(5, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyNotInScope(model, x11Ref[1]); VerifyNotInScope(model, x11Ref[2]); VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(5, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]); VerifyNotInScope(model, x12Ref[3]); VerifyNotInScope(model, x12Ref[4]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]); VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Decl.Length); Assert.Equal(3, x15Ref.Length); for (int i = 0; i < x15Ref.Length; i++) { VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]); } [Fact] public void Scope_SwitchLabelGuard_02() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_03() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): while (TakeOutParam(x1, out var y1) && Print(y1)) break; break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_04() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): do val = 0; while (TakeOutParam(x1, out var y1) && Print(y1)); break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_05() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): lock ((object)TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_06() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): if (TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): switch (TakeOutParam(x1, out var y1)) { default: break; } System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_08() { var source = @" public class X { public static void Main() { foreach (var x in Test(1)) {} } static System.Collections.IEnumerable Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): yield return TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_09() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z1 = x1 > 0 & TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_10() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): a: TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (14,1): warning CS0164: This label has not been referenced // a: TakeOutParam(x1, out var y1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_11() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): return TakeOutParam(x1, out var y1) && Print(y1); System.Console.WriteLine(y1); break; } return false; } static bool Print<T>(T x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (15,17): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_12() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { try { switch (val) { case 1 when TakeOutParam(123, out var x1): throw Dummy(TakeOutParam(x1, out var y1), y1); System.Console.WriteLine(y1); break; } } catch {} return false; } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (17,21): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_13() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_14() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelPattern_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test8(object val) { switch (val) { case int x8 when Dummy(x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case int x13 when Dummy(x13): Dummy(x13); break; } } void Test14(object val) { switch (val) { case int x14 when Dummy(x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test16(object val) { switch (val) { case int x16 when Dummy(x16): case 1 when Dummy(TakeOutParam(true, out var x16), x16): Dummy(x16); break; } } void Test17(object val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x17), x17): case int x17 when Dummy(x17): Dummy(x17); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,64): error CS0128: A local variable named 'x8' is already defined in this scope // when Dummy(x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64), // (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x13 when Dummy(x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22), // (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x14 when Dummy(x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22), // (51,58): error CS0128: A local variable named 'x16' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58), // (51,64): error CS0165: Use of unassigned local variable 'x16' // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64), // (62,22): error CS0128: A local variable named 'x17' is already defined in this scope // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22), // (62,37): error CS0165: Use of unassigned local variable 'x17' // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyNotAnOutLocal(model, x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]); VerifyNotAnOutLocal(model, x13Ref[3]); VerifyNotAnOutLocal(model, x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").Single(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(4, x14Ref.Length); VerifyNotAnOutLocal(model, x14Ref[0]); VerifyNotAnOutLocal(model, x14Ref[1]); VerifyNotAnOutLocal(model, x14Ref[2]); VerifyNotAnOutLocal(model, x14Ref[3]); VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x16Decl = GetOutVarDeclarations(tree, "x16").Single(); var x16Ref = GetReferences(tree, "x16").ToArray(); Assert.Equal(3, x16Ref.Length); for (int i = 0; i < x16Ref.Length; i++) { VerifyNotAnOutLocal(model, x16Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x16Decl); var x17Decl = GetOutVarDeclarations(tree, "x17").Single(); var x17Ref = GetReferences(tree, "x17").ToArray(); Assert.Equal(3, x17Ref.Length); VerifyModelForOutVar(model, x17Decl, x17Ref); } [Fact] public void Scope_ThrowStatement_01() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1() { throw Dummy(TakeOutParam(true, out var x1), x1); { throw Dummy(TakeOutParam(true, out var x1), x1); } throw Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { throw Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { throw Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); throw Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { throw Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // throw Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // throw Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) throw Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) throw Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); throw Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { throw Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52), // (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48), // (21,21): error CS0841: Cannot use local variable 'x2' before it is declared // throw Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21), // (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48), // (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ThrowStatement_02() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1(bool val) { if (val) throw Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ThrowStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@" throw Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(TakeOutParam(""throw"", out var x2), x2); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(TakeOutParam(""throw 1"", out var x2), x2); if (!val) { throw Dummy(TakeOutParam(""throw 2"", out var x2), x2); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Using_01() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49), // (35,22): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53), // (68,35): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35), // (86,35): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (var d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (var d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (var d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72), // (35,45): error CS0841: Cannot use local variable 'x6' before it is declared // using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76), // (68,58): error CS0103: The name 'y10' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58), // (86,58): error CS0103: The name 'y12' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,69): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_04() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,58): error CS0128: A local variable named 'x1' is already defined in this scope // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (12,63): error CS0841: Cannot use local variable 'x1' before it is declared // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63), // (20,73): error CS0128: A local variable named 'x2' is already defined in this scope // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73), // (20,78): error CS0165: Use of unassigned local variable 'x2' // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_Using_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } void Test3() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4)) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void Scope_While_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { while (TakeOutParam(true, out var x1) && x1) { Dummy(x1); } } void Test2() { while (TakeOutParam(true, out var x2) && x2) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); while (TakeOutParam(true, out var x4) && x4) Dummy(x4); } void Test6() { while (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { while (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { while (TakeOutParam(true, out var x8) && x8) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { while (TakeOutParam(true, out var x9) && x9) { Dummy(x9); while (TakeOutParam(true, out var x9) && x9) // 2 Dummy(x9); } } void Test10() { while (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // while (TakeOutParam(y11, out var x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { while (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // while (TakeOutParam(y13, out var x13)) // let y13 = 12; //} void Test14() { while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43), // (35,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47), // (68,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29), // (86,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_While_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) while (TakeOutParam(true, out var x1)) { ; } x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_While_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@" while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) f = false; f = true; if (f) { while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 4"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Yield_01() { var source = @" using System.Collections; public class X { public static void Main() { } object Dummy(params object[] x) { return null;} IEnumerable Test1() { yield return Dummy(TakeOutParam(true, out var x1), x1); { yield return Dummy(TakeOutParam(true, out var x1), x1); } yield return Dummy(TakeOutParam(true, out var x1), x1); } IEnumerable Test2() { yield return Dummy(x2, TakeOutParam(true, out var x2)); } IEnumerable Test3(int x3) { yield return Dummy(TakeOutParam(true, out var x3), x3); } IEnumerable Test4() { var x4 = 11; Dummy(x4); yield return Dummy(TakeOutParam(true, out var x4), x4); } IEnumerable Test5() { yield return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //IEnumerable Test6() //{ // let x6 = 11; // Dummy(x6); // yield return Dummy(TakeOutParam(true, out var x6), x6); //} //IEnumerable Test7() //{ // yield return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} IEnumerable Test8() { yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } IEnumerable Test9(bool y9) { if (y9) yield return Dummy(TakeOutParam(true, out var x9), x9); } IEnumerable Test11() { Dummy(x11); yield return Dummy(TakeOutParam(true, out var x11), x11); } IEnumerable Test12() { yield return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59), // (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55), // (23,28): error CS0841: Cannot use local variable 'x2' before it is declared // yield return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28), // (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55), // (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55), // (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13), // (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13), // (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92), // (72,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_Yield_02() { var source = @" using System.Collections; public class X { public static void Main() { } IEnumerable Test1() { if (true) yield return TakeOutParam(true, out var x1); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Yield_03() { var source = @" using System.Collections; public class X { public static void Main() { } void Dummy(params object[] x) {} IEnumerable Test1() { yield return 0; SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@" yield return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); yield return Dummy(TakeOutParam(""yield2"", out var x2), x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); if (f) { yield return Dummy(TakeOutParam(""yield2"", out var x1), x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_LabeledStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { a: Dummy(TakeOutParam(true, out var x1), x1); { b: Dummy(TakeOutParam(true, out var x1), x1); } c: Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { a: Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { a: Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); a: Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { a: Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); //a: Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ //a: Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) a: Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) a: Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); a: Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { a: Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (12,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1), // (14,1): warning CS0164: This label has not been referenced // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1), // (16,1): warning CS0164: This label has not been referenced // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (21,1): warning CS0164: This label has not been referenced // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (26,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (33,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (38,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x5), x5); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (59,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1), // (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1), // (65,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1), // (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1), // (73,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (80,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x11), x11); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1), // (85,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x12), x12); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_LabeledStatement_02() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) a: Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1), // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9), // (13,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_LabeledStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@" a: b: Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { a: b: c:Test2(Test1(out int x1), x1); System.Console.Write(x1); return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics( // (11,1): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1), // (11,4): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4), // (11,7): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void DataFlow_01() { var text = @" public class Cls { public static void Main() { Test(out int x1, x1); } static void Test(out int x, int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_02() { var text = @" public class Cls { public static void Main() { Test(out int x1, ref x1); } static void Test(out int x, ref int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // ref x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_03() { var text = @" public class Cls { public static void Main() { Test(out int x1); var x2 = 1; } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used // var x2 = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var dataFlow = model.AnalyzeDataFlow(x2Decl); Assert.True(dataFlow.Succeeded); Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString()); Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString()); } [Fact] public void TypeMismatch_01() { var text = @" public class Cls { public static void Main() { Test(out int x1); } static void Test(out short x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short' // Test(out int x1); Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_01() { var text = @" public class Cls { public static void Main() { Test(int x1); Test(ref int x2); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,14): error CS1525: Invalid expression term 'int' // Test(int x1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // Test(int x1); Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18), // (7,18): error CS1525: Invalid expression term 'int' // Test(ref int x2); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // Test(ref int x2); Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22), // (6,18): error CS0103: The name 'x1' does not exist in the current context // Test(int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18), // (7,22): error CS0103: The name 'x2' does not exist in the current context // Test(ref int x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void Parse_02() { var text = @" public class Cls { public static void Main() { Test(out int x1.); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,24): error CS1003: Syntax error, ',' expected // Test(out int x1.); Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_03() { var text = @" public class Cls { public static void Main() { Test(out System.Collections.Generic.IEnumerable<System.Int32>); } static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable // Test(out System.Collections.Generic.IEnumerable<System.Int32>); Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void GetAliasInfo_01() { var text = @" using a = System.Int32; public class Cls { public static void Main() { Test1(out a x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GetAliasInfo_02() { var text = @" using var = System.Int32; public class Cls { public static void Main() { Test1(out var x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void VarIsNotVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out var x) { x = new var() {val = 123}; return null; } static void Test2(object x, var y) { System.Console.WriteLine(y.val); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void VarIsNotVar_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test1' does not exist in the current context // Test1(out var x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9), // (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0 // public int val; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void SimpleVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static void Test2(object x, object y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0103: The name 'Test1' does not exist in the current context // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_03() { var text = @" public class Cls { public static void Main() { Test1(out var x1, out x1); } static object Test1(out int x, out int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // out x1); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_04() { var text = @" public class Cls { public static void Main() { Test1(out var x1, Test1(out x1, 3)); } static object Test1(out int x, int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // Test1(out x1, Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(ref int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_07() { var text = @" public class Cls { public static void Main() { dynamic x = null; Test2(x.Test1(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x.Test1(out var x1), Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_08() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var x1), x1); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_09() { var text = @" public class Cls { public static void Main() { Test2(new System.Action(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,37): error CS0149: Method name expected // Test2(new System.Action(out var x1), Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void ConstructorInitializers_01() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x, object y) { System.Console.WriteLine(y); } public Test2() : this(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : this(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26) ); var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); var typeInfo = model.GetTypeInfo(initializer); var symbolInfo = model.GetSymbolInfo(initializer); var group = model.GetMemberGroup(initializer); Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936 } [Fact] public void ConstructorInitializers_02() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { public Test2(object x, object y) { System.Console.WriteLine(y); } } class Test3 : Test2 { public Test3() : base(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : base(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26) ); } [Fact] public void ConstructorInitializers_03() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} class Test2 { Test2(out int x) { x = 2; } public Test2() : this(out var x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void ConstructorInitializers_04() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} class Test2 { public Test2(out int x) { x = 1; } } class Test3 : Test2 { public Test3() : base(out var x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_05() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(System.Func<object> x) { System.Console.WriteLine(x()); } public Test2() : this(() => { Test1(out var x1); return x1; }) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_06() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_07() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_08() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (23,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(23, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer(); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular) .GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.True(analyzer.ActionFired); } private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer { public bool ActionFired { get; private set; } private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer); } private void Handle(SyntaxNodeAnalysisContext context) { ActionFired = true; var tree = context.Node.SyntaxTree; var model = context.SemanticModel; var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent; SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl)); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0])); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1])); } } [Fact] public void ConstructorInitializers_09() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_10() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_11() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (21,37): error CS0165: Use of unassigned local variable 'x1' // => System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_12() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_13() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_14() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_15() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_16() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_17() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_14() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_15() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var var), var); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var varDecl = GetOutVarDeclaration(tree, "var"); var varRef = GetReferences(tree, "var").Skip(1).Single(); VerifyModelForOutVar(model, varDecl, varRef); } [Fact] public void SimpleVar_16() { var text = @" public class Cls { public static void Main() { if (Test1(out var x1)) { System.Console.WriteLine(x1); } } static bool Test1(out int x) { x = 123; return true; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void VarAndBetterness_01() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); Test2(out var x2, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, string y) { x = 124; System.Console.WriteLine(x); return null; } static object Test2(out int x, string y) { x = 125; System.Console.WriteLine(x); return null; } static object Test2(out short x, object y) { x = 126; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); VerifyModelForOutVar(model, x2Decl); } [Fact] public void VarAndBetterness_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, object y) { x = 124; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)' // Test1(out var x1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.ArgIterator x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_03() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25), // (6,16): 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. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void RestrictedTypes_04() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out System.ArgIterator x1), x1); var x = default(System.ArgIterator); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out System.ArgIterator x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25), // (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // var x = default(System.ArgIterator); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9), // (6,16): 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. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ElementAccess_01() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out var x1]); Test2(x1); Test2(x[out var _]); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25), // (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21), // (9,21): error CS8183: Cannot infer the type of implicitly-typed discard. // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21) ); } [Fact] public void PointerAccess_01() { var text = @" public class Cls { public static unsafe void Main() { int* p = (int*)0; Test2(p[out var x1]); Test2(x1); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25) ); } [Fact] public void ElementAccess_02() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out int x1], x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21), // (7,21): error CS0165: Use of unassigned local variable 'x1' // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21) ); } [Fact] [WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")] public void MissingArgumentAndNamedOutVarArgument() { var source = @"class Program { public static void Main(string[] args) { if (M(s: out var s)) { string s2 = s; } } public static bool M(int i, out string s) { s = i.ToString(); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)' // if (M(s: out var s)) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13) ); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_01() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x); System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_02() { var text = @" public class Cls { public static void Main() { var y = Test1(out int x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_03() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_04() { var text = @" public class Cls { public static void Main() { for (var y = Test1(out var x) + x; y != 0 ; y = 0) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_05() { var text = @" public class Cls { public static void Main() { foreach (var y in new [] {Test1(out var x) + x}) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_06() { var text = @" public class Cls { public static void Main() { Test1(x: 1, out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21), // (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_07() { var text = @" public class Cls { public static void Main() { int x = 0; Test1(y: ref x, y: out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)' // Test1(y: ref x, y: out var y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); var yRef = GetReferences(tree, "y").ToArray(); Assert.Equal(3, yRef.Length); Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString()); VerifyModelForOutVar(model, yDecl, yRef[2]); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamic() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int z]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @"{ // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) //z IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret }"); } [Fact] public void IndexingDynamicWithDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @" { // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret } "); } [Fact] public void IndexingDynamicWithVarDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out var _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23) ); } [Fact] public void IndexingDynamicWithShortDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out _]; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutVar() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.True(x1.Type.IsErrorType()); VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var x = d[out var x1] + x1; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutInt() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void OutVariableDeclarationInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; return 2; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.2 ret } // i = 3; return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.3 stind.i4 ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 4; return 5; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.5 ret } // i = 6; return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.6 stind.i4 ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} x1] + "" "" + x1); ia.P[out {0} x2] = 4; Console.WriteLine(x2); Console.WriteLine(ia[out {0} x3] + "" "" + x3); ia[out {0} x4] = 4; Console.WriteLine(x4); }} }}"; string[] fillIns = new[] { "int", "var" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString()); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString()); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(1, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString()); CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"2 1 3 5 4 6") .VerifyIL("B.Main()", @"{ // Code size 113 (0x71) .maxstack 4 .locals init (int V_0, //x1 int V_1, //x2 int V_2, //x3 int V_3, //x4 int V_4) IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: callvirt ""int IA.P[out int].get"" IL_000d: stloc.s V_4 IL_000f: ldloca.s V_4 IL_0011: call ""string int.ToString()"" IL_0016: ldstr "" "" IL_001b: ldloca.s V_0 IL_001d: call ""string int.ToString()"" IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: dup IL_002d: ldloca.s V_1 IL_002f: ldc.i4.4 IL_0030: callvirt ""void IA.P[out int].set"" IL_0035: ldloc.1 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: dup IL_003c: ldloca.s V_2 IL_003e: callvirt ""int IA.this[out int].get"" IL_0043: stloc.s V_4 IL_0045: ldloca.s V_4 IL_0047: call ""string int.ToString()"" IL_004c: ldstr "" "" IL_0051: ldloca.s V_2 IL_0053: call ""string int.ToString()"" IL_0058: call ""string string.Concat(string, string, string)"" IL_005d: call ""void System.Console.WriteLine(string)"" IL_0062: ldloca.s V_3 IL_0064: ldc.i4.4 IL_0065: callvirt ""void IA.this[out int].set"" IL_006a: ldloc.3 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret }"); } } [ClrOnlyFact] public void OutVariableDiscardInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; System.Console.WriteLine(11); return 111; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x06F ret } // i = 2; System.Console.Write(22); return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.2 stind.i4 ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 3; System.Console.WriteLine(33) return 333; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.3 stind.i4 ldc.i4.s 33 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x14D ret } // i = 4; System.Console.WriteLine(44); return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.s 44 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} _]); ia.P[out {0} _] = 4; Console.WriteLine(ia[out {0} _]); ia[out {0} _] = 4; }} }}"; string[] fillIns = new[] { "int", "var", "" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"11 111 22 33 333 44") .VerifyIL("B.Main()", @" { // Code size 58 (0x3a) .maxstack 3 .locals init (A V_0, //a IA V_1, //ia int V_2) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloca.s V_2 IL_000c: callvirt ""int IA.P[out int].get"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ldloc.1 IL_0018: ldloca.s V_2 IL_001a: ldc.i4.4 IL_001b: callvirt ""void IA.P[out int].set"" IL_0020: nop IL_0021: ldloc.1 IL_0022: ldloca.s V_2 IL_0024: callvirt ""int IA.this[out int].get"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ldloc.1 IL_0030: ldloca.s V_2 IL_0032: ldc.i4.4 IL_0033: callvirt ""void IA.this[out int].set"" IL_0038: nop IL_0039: ret }"); } } [Fact] public void ElementAccess_04() { var text = @" using System.Collections.Generic; public class Cls { public static void Main() { var list = new Dictionary<int, long> { [out var x1] = 3, [out var _] = 4, [out _] = 5 }; System.Console.Write(x1); System.Console.Write(_); { int _ = 1; var list2 = new Dictionary<int, long> { [out _] = 6 }; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var x1] = 3, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18), // (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var _] = 4, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18), // (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out _] = 5 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18), // (14,30): error CS0103: The name '_' does not exist in the current context // System.Console.Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30), // (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword // var list2 = new Dictionary<int, long> { [out _] = 6 }; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58) ); } [Fact] public void ElementAccess_05() { var text = @" public class Cls { public static void Main() { int[out var x1] a = null; // fatal syntax error - 'out' is skipped int b(out var x2) = null; // parsed as a local function with syntax error int c[out var x3] = null; // fatal syntax error - 'out' is skipped int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator x4 = 0; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count()); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); compilation.VerifyDiagnostics( // (6,13): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13), // (6,21): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21), // (7,27): error CS1002: ; expected // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27), // (7,27): error CS1525: Invalid expression term '=' // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27), // (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14), // (8,15): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15), // (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19), // (8,23): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23), // (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23), // (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17), // (10,17): error CS1003: Syntax error, '[' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17), // (10,28): error CS1003: Syntax error, ']' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28), // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12), // (6,17): error CS0103: The name 'var' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17), // (6,21): error CS0103: The name 'x1' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21), // (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body. // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13), // (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19), // (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29), // (8,19): error CS0103: The name 'var' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19), // (8,23): error CS0103: The name 'x3' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23), // (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13), // (6,25): warning CS0219: The variable 'a' is assigned but its value is never used // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25), // (10,13): warning CS0168: The variable 'd' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13), // (10,16): warning CS0168: The variable 'e' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16), // (7,13): warning CS8321: The local function 'b' is declared but never used // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13) ); } [Fact] public void ElementAccess_06() { var text = @" public class Cls { public static void Main() { { int[] e = null; var z1 = e?[out var x1]; x1 = 1; } { int[][] e = null; var z2 = e?[out var x2]?[out var x3]; x2 = 1; x3 = 2; } { int[][] e = null; var z3 = e?[0]?[out var x4]; x4 = 1; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var x2Decl = GetOutVarDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29), // (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33), // (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29), // (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'. // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33), // (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33), // (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'. // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37) ); } [Fact] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[out var x1, x1]; //fixed int F2[3 is int x2 ? x2 : 3]; //fixed int F2[3 is int x3 ? 3 : 3, x3]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Empty(GetOutVarDeclarations(tree, "x1")); compilation.VerifyDiagnostics( // (4,18): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18), // (4,26): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26), // (4,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17), // (4,22): error CS0103: The name 'var' does not exist in the current context // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22) ); } [Fact] public void Scope_DeclaratorArguments_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { int d,e(Dummy(TakeOutParam(true, out var x1), x1)); } void Test4() { var x4 = 11; Dummy(x4); int d,e(Dummy(TakeOutParam(true, out var x4), x4)); } void Test6() { int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); } void Test8() { int d,e(Dummy(TakeOutParam(true, out var x8), x8)); System.Console.WriteLine(x8); } void Test14() { int d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // int d,e(Dummy(TakeOutParam(true, out var x4), x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (30,34): error CS0165: Use of unassigned local variable 'x8' // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl) { Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl)); } private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls) { foreach (var decl in decls) { AssertContainedInDeclaratorArguments(decl); } } [Fact] public void Scope_DeclaratorArguments_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d, x1( Dummy(TakeOutParam(true, out var x1), x1)); Dummy(x1); } void Test2() { object d, x2( Dummy(TakeOutParam(true, out var x2), x2)); Dummy(x2); } void Test3() { object x3, d( Dummy(TakeOutParam(true, out var x3), x3)); Dummy(x3); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,13): error CS0818: Implicitly-typed variables must be initialized // var d, x1( Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13), // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (21,15): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15), // (27,54): error CS0128: A local variable named 'x3' is already defined in this scope // Dummy(TakeOutParam(true, out var x3), x3)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54), // (28,15): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1( Dummy(x1)); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2(Dummy(x3)); } void Test4() { object d1,e(Dummy(x4)], d2(Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1( Dummy(x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (14,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1,e(Dummy(x4)], Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 (Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (13,27): error CS0165: Use of unassigned local variable 'x1' // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59), // (26,27): error CS0165: Use of unassigned local variable 'x3' // d2 = Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y, y1(Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single(); Assert.Equal("var y1", y1.ToTestDisplayString()); Assert.True(((ILocalSymbol)y1).Type.IsErrorType()); } [Fact] public void Scope_DeclaratorArguments_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d,e(TakeOutParam(true, out var x1) && x1 != null); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13), // (11,17): error CS0818: Implicitly-typed variables must be initialized // var d,e(TakeOutParam(true, out var x1) && x1 != null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e); Assert.Equal("var e", symbol.ToTestDisplayString()); Assert.True(symbol.Type.IsErrorType()); } [Fact] [WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")] public void Scope_DeclaratorArguments_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)]; System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); AssertContainedInDeclaratorArguments(y1Decl); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType()); } [Fact] [WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")] public void Scope_DeclaratorArguments_08() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool a, b( Dummy(TakeOutParam(true, out var x1) && x1) );;) { Dummy(x1); } } void Test2() { for (bool a, b( Dummy(TakeOutParam(true, out var x2) && x2) );;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool a, b( Dummy(TakeOutParam(true, out var x4) && x4) );;) Dummy(x4); } void Test6() { for (bool a, b( Dummy(x6 && TakeOutParam(true, out var x6)) );;) Dummy(x6); } void Test7() { for (bool a, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool a, b( Dummy(TakeOutParam(true, out var x8) && x8) );;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool a1, b1( Dummy(TakeOutParam(true, out var x9) && x9) );;) { Dummy(x9); for (bool a2, b2( Dummy(TakeOutParam(true, out var x9) && x9) // 2 );;) Dummy(x9); } } void Test10() { for (bool a, b( Dummy(TakeOutParam(y10, out var x10)) );;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool a, b( // Dummy(TakeOutParam(y11, out var x11)) // );;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool a, b( Dummy(TakeOutParam(y12, out var x12)) );;) var y12 = 12; } //void Test13() //{ // for (bool a, b( // Dummy(TakeOutParam(y13, out var x13)) // );;) // let y13 = 12; //} void Test14() { for (bool a, b( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) );;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_09() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { for (bool d, x4( Dummy(TakeOutParam(true, out var x4) && x4) );;) {} } void Test7() { for (bool x7 = true, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) {} } void Test8() { for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)], b2(Dummy(TakeOutParam(true, out var x8) && x8)); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2(Dummy(TakeOutParam(true, out var x9) && x9)); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47), // (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47), // (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used // for (bool x7 = true, b( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19), // (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2(Dummy(TakeOutParam(true, out var x8) && x8)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52), // (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47), // (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47), // (37,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23), // (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47), // (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl[0]); AssertContainedInDeclaratorArguments(x8Decl[1]); VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]); } [Fact] public void Scope_DeclaratorArguments_10() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,e(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (var d,e(Dummy(TakeOutParam(true, out var x2), x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Dummy(x4); } void Test6() { using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d,e(Dummy(TakeOutParam(true, out var x8), x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d,a(Dummy(TakeOutParam(true, out var x9), x9))) { Dummy(x9); using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Dummy(x9); } } void Test10() { using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) var y12 = 12; } //void Test13() //{ // using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13))) // let y13 = 12; //} void Test14() { using (var d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); AssertContainedInDeclaratorArguments(x10Decl); VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_11() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope // using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope // using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); AssertContainedInDeclaratorArguments(x2Decl); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_DeclaratorArguments_12() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } void Test3() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2(Dummy(TakeOutParam(true, out var x4), x4))) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_13() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Dummy(x4); } void Test6() { fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9))) { Dummy(x9); fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Dummy(x9); } } void Test10() { fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11)))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) var y12 = 12; } //void Test13() //{ // fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13)))) // let y13 = 12; //} void Test14() { fixed (int* p,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_14() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* d,x1( Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)], x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p(Dummy(TakeOutParam(true, out var x3) && x3))) { Dummy(x3); } } void Test4() { fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)], p2(Dummy(TakeOutParam(true, out var x4) && x4))) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Scope_DeclaratorArguments_15() { var source = @" public class X { public static void Main() { } bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; bool Test4 [x4 && TakeOutParam(4, out var x4)]; bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } private static void VerifyModelNotSupported( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax)); Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var identifierText = decl.Identifier().ValueText; Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any()); Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText)); Assert.Null(model.GetSymbolInfo(decl.Type).Symbol); AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null); VerifyModelNotSupported(model, references); } private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references) { foreach (var reference in references) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart)); Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType()); } } [Fact] public void Scope_DeclaratorArguments_16() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; fixed bool Test4 [x4 && TakeOutParam(4, out var x4)]; fixed bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; fixed bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; fixed bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; fixed bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField, (int)ErrorCode.ERR_NoImplicitConv }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 [x4 && TakeOutParam(4, out var x4)]; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (20,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 [Dummy(x7, 2)]; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25), // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_17() { var source = @" public class X { public static void Main() { } const bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; const bool Test4 [x4 && TakeOutParam(4, out var x4)]; const bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; const bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; const bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; const bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_18() { var source = @" public class X { public static void Main() { } event bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; event bool Test4 [x4 && TakeOutParam(4, out var x4)]; event bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; event bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; event bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; event bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.ERR_EventNotDelegate, (int)ErrorCode.WRN_UnreferencedEvent }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_19() { var source = @" public unsafe struct X { public static void Main() { } fixed bool d[2], Test3 (out var x3); } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (8,28): error CS1003: Syntax error, '[' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28), // (8,39): error CS1003: Syntax error, ']' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39), // (8,33): error CS8185: A declaration is not allowed in this context. // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_20() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3[out var x3]; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,22): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22), // (8,30): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30), // (8,21): error CS7092: A fixed buffer may only have one dimension. // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21), // (8,26): error CS0103: The name 'var' does not exist in the current context // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); } [Fact] public void StaticType() { var text = @" public class Cls { public static void Main() { Test1(out StaticType x1); } static object Test1(out StaticType x) { throw new System.NotSupportedException(); } static class StaticType {} }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters // static object Test1(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19), // (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType' // Test1(out StaticType x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19) ); } [Fact] public void GlobalCode_Catch_01() { var source = @" bool Dummy(params object[] x) {return true;} try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34), // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42), // (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13), // (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Catch_02() { var source = @" try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Block_01() { string source = @" { H.TakeOutParam(1, out var x1); H.Dummy(x1); } object x2; { H.TakeOutParam(2, out var x2); H.Dummy(x2); } { H.TakeOutParam(3, out var x3); } H.Dummy(x3); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,8): warning CS0168: The variable 'x2' is declared but never used // object x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8), // (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31), // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } } [Fact] public void GlobalCode_Block_02() { string source = @" { H.TakeOutParam(1, out var x1); System.Console.WriteLine(x1); Test(); void Test() { System.Console.WriteLine(x1); } } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_For_01() { var source = @" bool Dummy(params object[] x) {return true;} for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } for ( // 2 Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42), // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_For_02() { var source = @" bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_Foreach_01() { var source = @"using static Helpers; System.Collections.IEnumerable Dummy(params object[] x) {return null;} foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } static class Helpers { public static bool TakeOutParam(int y, out int x) { x = y; return true; } public static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Foreach_02() { var source = @" bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_01() { var source = @" bool Dummy(params object[] x) {return true;} Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0)); Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) && TakeOutParam(o2, out var x5) && x5 > 0)); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0)); Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0), x7); Dummy(x7, 2); Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out var x9) && x9 > 0), x9); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) && x10 > 0), TakeOutParam(true, out var x10), x10); var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) && x11 > 0), x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutField(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutField(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutField(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7), // (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7), // (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79), // (37,9): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9), // (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13), // (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void GlobalCode_Lambda_02() { var source = @" System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); System.Console.WriteLine(l()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_03() { var source = @" System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Query_01() { var source = @" using System.Linq; bool Dummy(params object[] x) {return true;} var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutField(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutField(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutField(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutField(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutField(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutField(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutField(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutField(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutField(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutField(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutField(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutField(model, y10Decl, y10Ref[0]); VerifyNotAnOutField(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutField(model, y11Decl, y11Ref[0]); VerifyNotAnOutField(model, y11Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7), // (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18), // (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } } [Fact] public void GlobalCode_Query_02() { var source = @" using System.Linq; var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutField(model, yDecl, yRef); } [Fact] public void GlobalCode_Using_01() { var source = @" System.IDisposable Dummy(params object[] x) {return null;} using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_Using_02() { var source = @" using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void GlobalCode_ExpressionStatement_01() { string source = @" H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out int x2); H.TakeOutParam(3, out int x3); object x3; H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } private static void AssertNoGlobalStatements(SyntaxTree tree) { Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()); } [Fact] public void GlobalCode_ExpressionStatement_02() { string source = @" H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out var x2); H.TakeOutParam(3, out var x3); object x3; H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ExpressionStatement_03() { string source = @" System.Console.WriteLine(x1); H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_IfStatement_01() { string source = @" if (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out int x2)) {} if (H.TakeOutParam(3, out int x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} if (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); int x6 = 6; if (H.Dummy()) { string x6 = ""6""; H.Dummy(x6); } void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (30,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17), // (30,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21), // (30,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used // int x6 = 6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5), // (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x6 = "6"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12), // (33,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_IfStatement_02() { string source = @" if (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out var x2)) {} if (H.TakeOutParam(3, out var x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} void Test() { H.Dummy(x1, x2, x3, x4, x5); } if (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,29): error CS0841: Cannot use local variable 'x5' before it is declared // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29), // (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } } [Fact] public void GlobalCode_IfStatement_03() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_IfStatement_04() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_YieldReturnStatement_01() { string source = @" yield return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out int x2); yield return H.TakeOutParam(3, out int x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_YieldReturnStatement_02() { string source = @" yield return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out var x2); yield return H.TakeOutParam(3, out var x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_01() { string source = @" return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out int x2); return H.TakeOutParam(3, out int x3); object x3; return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_02() { string source = @" return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out var x2); return H.TakeOutParam(3, out var x3); object x3; return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_03() { string source = @" System.Console.WriteLine(x1); Test(); return H.Dummy(H.TakeOutParam(1, out var x1), x1); void Test() { System.Console.WriteLine(x1); } class H { public static bool Dummy(object x, object y) { System.Console.WriteLine(y); return true; } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_ThrowStatement_01() { string source = @" throw H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out int x2); throw H.TakeOutParam(3, out int x3); object x3; throw H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ThrowStatement_02() { string source = @" throw H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out var x2); throw H.TakeOutParam(3, out var x3); object x3; throw H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_SwitchStatement_01() { string source = @" switch (H.TakeOutParam(1, out int x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out int x2)) {default: break;} switch (H.TakeOutParam(3, out int x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {default: break;} switch (H.TakeOutParam(51, out int x5)) { default: H.TakeOutParam(""52"", out string x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_02() { string source = @" switch (H.TakeOutParam(1, out var x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out var x2)) {default: break;} switch (H.TakeOutParam(3, out var x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {default: break;} switch (H.TakeOutParam(51, out var x5)) { default: H.TakeOutParam(""52"", out var x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_03() { string source = @" System.Console.WriteLine(x1); switch (H.TakeOutParam(1, out var x1)) { default: H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); break; } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_WhileStatement_01() { string source = @" while (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out int x2)) {} while (H.TakeOutParam(3, out int x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} while (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out int x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_02() { string source = @" while (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out var x2)) {} while (H.TakeOutParam(3, out var x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} while (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out var x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_03() { string source = @" while (H.TakeOutParam(1, out var x1)) { System.Console.WriteLine(x1); break; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_DoStatement_01() { string source = @" do {} while (H.TakeOutParam(1, out int x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out int x2)); do {} while (H.TakeOutParam(3, out int x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))); do { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } while (H.TakeOutParam(51, out int x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out int x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out int x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_02() { string source = @" do {} while (H.TakeOutParam(1, out var x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out var x2)); do {} while (H.TakeOutParam(3, out var x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))); do { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } while (H.TakeOutParam(51, out var x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out var x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out var x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_03() { string source = @" int f = 1; do { } while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3); int Test(int x) { System.Console.WriteLine(x); return x; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2 3").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_LockStatement_01() { string source = @" lock (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out int x2)) {} lock (H.TakeOutParam(3, out int x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} lock (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_02() { string source = @" lock (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out var x2)) {} lock (H.TakeOutParam(3, out var x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} lock (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_03() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_LockStatement_04() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_DeconstructionDeclarationStatement_01() { string source = @" (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); Test(); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (16,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref[0]); } } [Fact] public void GlobalCode_LabeledStatement_01() { string source = @" a: H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out int x2); c: H.TakeOutParam(3, out int x3); object x3; d: H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_02() { string source = @" a: H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out var x2); c: H.TakeOutParam(3, out var x3); object x3; d: H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_03() { string source = @" System.Console.WriteLine(x1); a:b:c:H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_04() { string source = @" a: bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out int x2); e: bool f = H.TakeOutParam(3, out int x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); i: bool x5 = H.TakeOutParam(5, out int x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [Fact] public void GlobalCode_LabeledStatement_05() { string source = @" a: bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out var x2); e: bool f = H.TakeOutParam(3, out var x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); i: bool x5 = H.TakeOutParam(5, out var x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void GlobalCode_LabeledStatement_06_Script() { string source = @" System.Console.WriteLine(x1); a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_06_SimpleProgram() { string source = @" a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_07() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_08() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out var x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out var x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), H.TakeOutParam(6, out var x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_09() { string source = @" System.Console.WriteLine(x1); a:b:c: var (d, e) = (H.TakeOutParam(1, out var x1), 1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_01() { string source = @" bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out int x2); bool f = H.TakeOutParam(3, out int x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 = H.TakeOutParam(5, out int x5); bool i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_02() { string source = @" bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out var x2); bool f = H.TakeOutParam(3, out var x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 = H.TakeOutParam(5, out var x5); bool i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_03() { string source = @" System.Console.WriteLine(x1); var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static var b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_05() { string source = @" bool b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_06() { string source = @" bool b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_07() { string source = @" Test(); bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); bool Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return false; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_PropertyDeclaration_01() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out int x2); bool f { get; } = H.TakeOutParam(3, out int x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 { get; } = H.TakeOutParam(5, out int x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_02() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out var x2); bool f { get; } = H.TakeOutParam(3, out var x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 { get; } = H.TakeOutParam(5, out var x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_03() { string source = @" System.Console.WriteLine(x1); bool d { get; set; } = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static bool b { get; } = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_05() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_06() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_01() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out int x2); event System.Action f = H.TakeOutParam(3, out int x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); event System.Action x5 = H.TakeOutParam(5, out int x5); event System.Action i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_02() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out var x2); event System.Action f = H.TakeOutParam(3, out var x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); event System.Action x5 = H.TakeOutParam(5, out var x5); event System.Action i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_03() { string source = @" System.Console.WriteLine(x1); event System.Action d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static event System.Action b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_05() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_06() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_07() { string source = @" Test(); event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); System.Action Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_DeclaratorArguments_01() { string source = @" bool a, b(out var x1); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_02() { string source = @" label: bool a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1), // (4,9): error CS0165: Use of unassigned local variable 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_03() { string source = @" event System.Action a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static System.Action Dummy(params object[] x) {return null;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_DeclaratorArguments_04() { string source = @" fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static int TakeOutParam<T>(T y, out T x) { x = y; return 3; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to 'b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12), // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_RestrictedType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out System.ArgIterator x2); class H { public static void TakeOutParam(out System.ArgIterator x) { x = default(System.ArgIterator); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public static void TakeOutParam(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37), // (5,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out System.ArgIterator x2); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20), // (3,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_StaticType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out StaticType x2); class H { public static void TakeOutParam(out StaticType x) { x = default(System.ArgIterator); } } static class StaticType{} "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (5,31): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out StaticType x2); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31), // (9,24): error CS0721: 'StaticType': static types cannot be used as parameters // public static void TakeOutParam(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24), // (3,24): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_InferenceFailure_01() { string source = @" H.TakeOutParam(out var x1, x1); class H { public static void TakeOutParam(out int x, long y) { x = 1; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.TakeOutParam(out var x1, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact] public void GlobalCode_InferenceFailure_02() { string source = @" var a = b; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_03() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = a; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = a; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_04() { string source = @" var a = x1; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single()); Assert.True(a.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32) ); } [Fact] public void GlobalCode_InferenceFailure_05() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = x1; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = H.TakeOutParam(out var x1, b); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single(); var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl); Assert.True(b.Type.IsErrorType()); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); Assert.False(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); } [Fact] public void GlobalCode_InferenceFailure_06() { string source = @" H.TakeOutParam(out var x1); class H { public static int TakeOutParam<T>(out T x) { x = default(T); return 123; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24), // (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3) ); compilation.GetDeclarationDiagnostics().Verify( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")] public void GlobalCode_InferenceFailure_07() { string source = @" H.M((var x1, int x2)); H.M(x1); class H { public static void M(object a) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10), // (2,6): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6), // (2,14): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14), // (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5), // (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object' // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5) ); compilation.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")] public void InferenceFailure_01() { string source = @" class H { object M1() => M(M(1), x1); static object M(object o1) => o1; static void M(object o1, object o2) {} } "; var node0 = SyntaxFactory.ParseCompilationUnit(source); var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var decl = SyntaxFactory.DeclarationExpression( type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")), designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1"))); var node1 = node0.ReplaceNode(one, decl); var tree = node1.SyntaxTree; Assert.NotNull(tree); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics( // (4,24): error CS8185: A declaration is not allowed in this context. // object M1() => M(M(varx1), x1); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24) ); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_AliasInfo_01() { string source = @" H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void GlobalCode_AliasInfo_02() { string source = @" using var = System.Int32; H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_03() { string source = @" using a = System.Int32; H.TakeOutParam(1, out a x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_04() { string source = @" H.TakeOutParam(1, out int x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_1() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out var x1): System.Console.WriteLine(x1); break; } } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case !TakeOutParam(3, out var x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_2() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out UndeclaredType x1): System.Console.WriteLine(x1); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19), // (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?) // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, false, references); } private static void VerifyModelForOutFieldDuplicate( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, true, references); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, bool duplicate, params IdentifierNameSyntax[] references) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(SymbolKind.Field, symbol.Kind); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText); var names = model.LookupNames(decl.SpanStart); if (duplicate) { Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, symbols.Single()); } Assert.Contains(decl.Identifier().ValueText, names); var local = (IFieldSymbol)symbol; var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement && (declarator.ArgumentList?.Contains(decl)).GetValueOrDefault(); // We're not able to get type information at such location (out var argument in global code) at this point // See https://github.com/dotnet/roslyn/issues/13569 AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type); foreach (var reference in references) { var referenceInfo = model.GetSymbolInfo(reference); symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText); if (duplicate) { Assert.Null(referenceInfo.Symbol); Assert.Contains(symbol, referenceInfo.CandidateSymbols); Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, referenceInfo.Symbol); Assert.Same(symbol, symbols.Single()); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); } if (!inFieldDeclaratorArgumentlist) { var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent; if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); } else { var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (dataFlow.Succeeded) { Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } } [Fact] public void MethodTypeArgumentInference_01() { var source = @" public class X { public static void Main() { TakeOutParam(out int a); TakeOutParam(out long b); } static void TakeOutParam<T>(out T x) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int64"); } [Fact] public void MethodTypeArgumentInference_02() { var source = @" public class X { public static void Main() { TakeOutParam(out var a); } static void TakeOutParam<T>(out T x) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out var a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9) ); } [Fact] public void MethodTypeArgumentInference_03() { var source = @" public class X { public static void Main() { long a = 0; TakeOutParam(out int b, a); int c; TakeOutParam(out c, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out int b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9), // (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out c, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9) ); } [Fact] public void MethodTypeArgumentInference_04() { var source = @" public class X { public static void Main() { byte a = 0; int b = 0; TakeOutParam(out int c, a); TakeOutParam(out b, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int32"); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void OutVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); } [Fact] public void OutVarDiscard() { var source = @" public class C { static void Main() { M(out int _); M(out var _); M(out _); } static void M(out int x) { x = 1; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.Single(); var model = comp.Compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); 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.GetTypeInfo(discard2).Type); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); comp.VerifyIL("C.Main()", @" { // Code size 22 (0x16) .maxstack 1 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: call ""void C.M(out int)"" IL_0007: ldloca.s V_0 IL_0009: call ""void C.M(out int)"" IL_000e: ldloca.s V_0 IL_0010: call ""void C.M(out int)"" IL_0015: ret } "); } [Fact] public void NamedOutVarDiscard() { var source = @" public class C { static void Main() { M(y: out string _, x: out int _); M(y: out var _, x: out var _); M(y: out _, x: out _); } static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); } [Fact] public void OutVarDiscardInCtor_01() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out int i1); new C(out int _); new C(out var _); new C(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); 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); Assert.Equal("int", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); 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("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact] public void OutVarDiscardInCtor_02() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out long x1); new C(out long _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long x1); Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19), // (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long _); Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19), // (7,19): error CS0165: Use of unassigned local variable 'x1' // new C(out long x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl); var discard1 = GetDiscardDesignations(tree).Single(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("long _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("long", declaration1.Type.ToString()); Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); } [Fact] public void OutVarDiscardAliasInfo_01() { var source = @" using alias1 = System.Int32; using var = System.Int32; public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString()); 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("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString()); } [Fact] public void OutVarDiscardAliasInfo_02() { var source = @" enum alias1 : long {} class var {} public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int' // new C(out alias1 _); Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19), // (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int' // new C(out var _); Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString()); Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); 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("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("var", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); } [Fact] public void OutVarDiscardInCtorInitializer() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C ""); } static void Main() { new Derived2(out int i2); new Derived3(out int i3); new Derived4(); } } public class Derived2 : C { public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); } } public class Derived3 : C { public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); } } public class Derived4 : C { public Derived4(out int i) : base(out _) { i = 4; } public Derived4() : this(out _) { System.Console.Write(""Derived4""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4"); } [Fact] public void DiscardNotRecognizedInOtherScenarios() { var source = @" public class C { void M<T>() { _.ToString(); M(_); _<T>.ToString(); (_<T>, _<T>) = (1, 2); M<_>(); new C() { _ = 1 }; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): error CS0103: The name '_' does not exist in the current context // _.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9), // (7,11): error CS0103: The name '_' does not exist in the current context // M(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11), // (8,9): error CS0103: The name '_' does not exist in the current context // _<T>.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9), // (9,10): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10), // (9,16): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16), // (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // M<_>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11), // (11,19): error CS0117: 'C' does not contain a definition for '_' // new C() { _ = 1 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19) ); } [Fact] public void TypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); System.Console.Write(t.GetType().ToString()); } static void Main() { M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "System.Int32"); } [Fact] public void UntypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); } static void Main() { M(out var _); M(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out var _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9), // (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9) ); } [Fact] public void PickOverloadWithTypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); } static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); } static void Main() { M(out object _); M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "object returning M. int returning M."); } [Fact] public void CannotPickOverloadWithUntypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; } static void M(out int x) { x = 2; } static void Main() { M(out var _); M(out _); M(out byte _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out var _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9), // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9), // (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object' // M(out byte _); Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15) ); } [Fact] public void NoOverloadWithDiscard() { var source = @" public class A { } public class B : A { static void M(A a) { a.M2(out A x); a.M2(out A _); } } public static class S { public static void M2(this A self, out B x) { x = null; } }"; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore }); comp.VerifyDiagnostics( // (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A x); Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18), // (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A _); Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18) ); } [Fact] [WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")] public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier() { var source = @" public class C { static void M(string x) { if(true) && int.TryParse(x, out int y)) id(iVal); // Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single(); Assert.Equal("x", x.ToString()); Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString()); } [Fact] public void DuplicateDeclarationInSwitchBlock() { var text = @" public class C { public static void Main(string[] args) { switch (args.Length) { case 0: M(M(out var x1), x1); M(M(out int x1), x1); break; case 1: M(M(out int x1), x1); break; } } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics( // (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29), // (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29), // (13,34): error CS0165: Use of unassigned local variable 'x1' // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x6Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x6Decl.Length); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]); } [Fact] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(int a, int b) => a+b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,75): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,75): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInAnonymousMethodParameterDefault() { var text = @" class C { public static void Main(int arg) { System.Action<bool, int> d1 = delegate ( bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }; System.Action<bool, int> d2 = delegate ( bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }; int x = z1 + z2; d1 = d2 = null; } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; } "; // the scope of an expression variable introduced in the default expression // of a lambda parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify( // (9,55): error CS0103: The name 'z1' does not exist in the current context // { var t = z1; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55), // (13,55): error CS0103: The name 'z2' does not exist in the current context // { var t = z2; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55), // (15,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17), // (15,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First(); Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString()); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void Scope_LocalFunction_Attribute_01() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_02() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_03() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_04() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_05() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_LocalFunction_Attribute_06() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_InvalidArrayDimensions01() { var text = @" public class Cls { public static void Main() { int x1 = 0; int[Test1(out int x1), x1] _1; int[Test1(out int x2), x2] x2; } static int Test1(out int x) { x = 1; return 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12), // (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27), // (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12), // (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13), // (7,27): warning CS0168: The variable 'x1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27), // (7,36): warning CS0168: The variable '_1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36), // (8,27): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27), // (8,36): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyNotAnOutLocal(model, x1Ref); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref); } [Fact] public void Scope_InvalidArrayDimensions_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using (int[] d = null) { Dummy(x1); } } void Test2() { using (int[] d = null) Dummy(x2); } void Test3() { var x3 = 11; Dummy(x3); using (int[] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 3; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16), // file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19), // file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // file.cs(14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16), // file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19), // file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51), // file.cs(21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16), // file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19), // file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51), // file.cs(30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using int[TakeOutParam(true, out var x1), x1] d = null; Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); using int[TakeOutParam(true, out var x2), x2] d = null; Dummy(x2); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9), // (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18), // (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19), // (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // (13,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15), // (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9), // (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18), // (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19), // (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46), // (21,46): warning CS0168: The variable 'x2' is declared but never used // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyNotAnOutLocal(model, x2Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true); } [Fact] public void Scope_InvalidArrayDimensions_04() { var source = @" public class X { public static void Main() { } bool Dummy(object x) {return true;} void Test1() { for (int[] a = null;;) Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); for (int[] a = null;;) Dummy(x2); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 2; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17), // file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18), // file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49), // file.cs(13,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19), // file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53), // file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17), // file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45), // file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18), // file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49), // file.cs(22,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19), // file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} unsafe void Test1() { fixed (int[TakeOutParam(true, out var x1), x1] d = null) { Dummy(x1); } } unsafe void Test2() { fixed (int[TakeOutParam(true, out var x2), x2] d = null) Dummy(x2); } unsafe void Test3() { var x3 = 11; Dummy(x3); fixed (int[TakeOutParam(true, out var x3), x3] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test1() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17), // (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19), // (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52), // (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56), // (14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test2() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17), // (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19), // (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52), // (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56), // (21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test3() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17), // (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19), // (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52), // (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56), // (30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void DeclarationInNameof_00() { var text = @" class C { public static void Main() { var x = nameof(M2(M1(out var x1), x1)).ToString(); } static int M1(out int z) => z = 1; static int M2(int a, int b) => 2; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,24): error CS8081: Expression does not have a name. // var x = nameof(M2(M1(out var x1), x1)).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "x1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(1, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DeclarationInNameof_01() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(object a, int b) => b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,83): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83), // (6,39): error CS8081: Expression does not have a name. // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30), // (6,69): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69), // (7,83): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83), // (7,39): error CS8081: Expression does not have a name. // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30), // (7,69): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02a() { var text = @" [My(C.M(nameof(C.M(out int z1)), z1), z1)] [My(C.M(nameof(C.M(out var z2)), z2), z2)] class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (2,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16), // (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5), // (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39), // (3,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16), // (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5), // (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02b() { var text1 = @" [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] "; var text2 = @" class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 }); compilation.VerifyDiagnostics( // (2,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26), // (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15), // (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49), // (3,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26), // (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15), // (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_03() { var text = @" class C { public static void Main(string[] args) { switch ((object)args.Length) { case !M(nameof(M(out int z1)), z1): System.Console.WriteLine(z1); break; case !M(nameof(M(out var z2)), z2): System.Console.WriteLine(z2); break; } } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (8,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28), // (8,18): error CS0150: A constant value is expected // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18), // (11,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28), // (11,18): error CS0150: A constant value is expected // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18), // (8,44): error CS0165: Use of unassigned local variable 'z1' // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44), // (11,44): error CS0165: Use of unassigned local variable 'z2' // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_04() { var text = @" class C { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); const bool c = (z1 + z2) == 0; public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (5,29): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29), // (5,20): error CS0133: The expression being assigned to 'C.b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20), // (6,21): error CS0103: The name 'z1' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21), // (6,26): error CS0103: The name 'z2' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26), // (4,29): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29), // (4,20): error CS0133: The expression being assigned to 'C.a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_05() { var text = @" class C { public static void Main(string[] args) { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); bool c = (z1 + z2) == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,33): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33), // (6,24): error CS0133: The expression being assigned to 'a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24), // (7,33): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33), // (7,24): error CS0133: The expression being assigned to 'b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24), // (6,49): error CS0165: Use of unassigned local variable 'z1' // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49), // (7,49): error CS0165: Use of unassigned local variable 'z2' // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_06() { var text = @" class C { public static void Main(string[] args) { string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); bool c = z1 == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,27): error CS8081: Expression does not have a name. // string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27), // (7,18): error CS0103: The name 'z1' does not exist in the current context // bool c = z1 == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "z1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, references: refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_01() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p => { weakRef.TryGetTarget(out var x); }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_02() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { weakRef.TryGetTarget(out var x); }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_03() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { void Local1 (Action<T> onNext = p3 => { weakRef.TryGetTarget(out var x); }) { } }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_04() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_05() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select (Action<T>)( p => { void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } ) ) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_06() { string source = @" class C { void M<T>() { System.Type t = typeof(int[p => { weakRef.TryGetTarget(out var x); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_07() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { weakRef.TryGetTarget(out var x); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_08() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { System.Type t3 = typeof(int[p3 => { weakRef.TryGetTarget(out var x); }]); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_09() { string source = @" class C { void M<T>() { System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_10() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[from p in y select (Action<T>)( p => { System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } ) ] ); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")] public void GetEnclosingBinderInternalRecovery_11() { var text = @" class Program { static void Main(string[] args) { foreach other(some().F(a => TestOutVar(out var x) ? x : 1)); } static void TestOutVar(out int a) { a = 0; } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, '(' expected // foreach Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16), // (7,60): error CS1515: 'in' expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60), // (7,60): error CS0230: Type and identifier are both required in a foreach statement // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60), // (7,60): error CS1525: Invalid expression term ';' // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60), // (7,60): error CS1026: ) expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xDecl = GetOutVarDeclaration(tree, "x"); var xRef = GetReferences(tree, "x", 1); VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString()); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates() { var source = @"using System; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Func<int, bool> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Expression() { var source = @"using System; using System.Linq.Expressions; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Expression<Func<int, bool>> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Query() { var source = @"using System.Linq; class C { static void M() { var c = from x in new[] { 1, 2, 3 } group x > 1 && F(out var y) && y == null by x; } static bool F(out object o) { o = null; return true; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public void SpeculativeSemanticModelWithOutDiscard() { var source = @"class C { static void F() { C.G(out _); } static void G(out object o) { o = null; } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var identifierBefore = GetReferences(tree, "G").Single(); Assert.Equal(tree, identifierBefore.Location.SourceTree); var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First(); var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);"); bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model); Assert.True(success); var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G"); Assert.Null(identifierAfter.Location.SourceTree); var info = model.GetSymbolInfo(identifierAfter); Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")] [WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")] public void GetForEachSymbolInfoWithOutVar() { var source = @"using System.Collections.Generic; public class C { void M() { foreach (var x in M2(out int i)) { } } IEnumerable<object> M2(out int j) { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachStatement); Assert.Equal("System.Object", info.ElementType.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); } [WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void DiscardAndArgList() { var text = @" using System; public class C { static void Main() { M(out _, __arglist(2, 3, true)); } static void M(out int x, __arglist) { x = 0; DumpArgs(new ArgIterator(__arglist)); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "23True"); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_01() { var text = @" public class C { static void Main() { M(1, __arglist(out int y)); M(2, __arglist(out var z)); System.Console.WriteLine(z); } static void M(int x, __arglist) { x = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(1, __arglist(out int y)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28), // (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32), // (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_02() { var text = @" public class C { static void Main() { __arglist(out int y); __arglist(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out int y); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23), // (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out int y); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9), // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // __arglist(out var z); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27), // (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out var z); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23), // (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out var z); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_01() { var text = @" public class C { static void M<T>() where T : new() { var x = new T(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z); Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)') Children(1): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_02() { var text = @" public class C { static void M<T>() where T : C, new() { var x = new T(out var z) {F1 = 1}; System.Console.WriteLine(z); } public int F1; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z) {F1 = 1}; Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z) {F1 = 1}", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}') Children(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1') Left: IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ConstructorBodyOperation() { var text = @" public class C { C() : this(out var x) { M(out var y); } => M(out var z); C (out int x){x=1;} void M (out int x){x=1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(out var x)", initializerSyntax.ToString()); compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree: @" IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation initializerOperation = model.GetOperation(initializerSyntax); Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind); Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent); Assert.Null(blockBodyOperation.Parent.Parent); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent); var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First(); Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);') Locals: Local_1: System.Int32 x Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Expression: IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MethodBodyOperation() { var text = @" public class C { int P { get {return M(out var x);} => M(out var y); } => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax); Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind); Assert.Null(expressionBodyOperation.Parent.Parent); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent); var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1); Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString()); Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900 var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);') BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyExpressionBodyOperation() { var text = @" public class C { int P => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", node3.ToString()); compilation.VerifyOperationTree(node3, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(node3).Parent); } [Fact] public void OutVarInConstructorUsedInObjectInitializer() { var source = @" public class C { public int Number { get; set; } public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { Number = i }; System.Console.WriteLine(c.Number); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] public void OutVarInConstructorUsedInCollectionInitializer() { var source = @" public class C : System.Collections.Generic.List<int> { public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { i, i, i }; System.Console.WriteLine(c[0]); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] [WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")] public void Issue49997() { var text = @" public class Cls { public static void Main() { if () .Test1().Test2(out var x1).Test3(); } } static class Ext { public static void Test3(this Cls x) {} } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last(); Assert.True(model.GetSymbolInfo(node).IsEmpty); } } internal static class OutVarTestsExtensions { internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self) { return (SingleVariableDesignationSyntax)self.Designation; } } }
1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Features/Core/Portable/NavigationBar/AbstractNavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract class AbstractNavigationBarItemService : INavigationBarItemService { protected abstract Task<ImmutableArray<RoslynNavigationBarItem>> GetItemsInCurrentProcessAsync(Document document, bool supportsCodeGeneration, CancellationToken cancellationToken); public async Task<ImmutableArray<RoslynNavigationBarItem>> GetItemsAsync(Document document, bool supportsCodeGeneration, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. We don't need the full solution synchronized over to the OOP // in order to get accurate navbar contents for this document. var result = await client.TryInvokeAsync<IRemoteNavigationBarItemService, ImmutableArray<SerializableNavigationBarItem>>( document.Project, (service, solutionInfo, cancellationToken) => service.GetItemsAsync(solutionInfo, document.Id, supportsCodeGeneration, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value.SelectAsArray(v => v.Rehydrate()) : ImmutableArray<RoslynNavigationBarItem>.Empty; } var items = await GetItemsInCurrentProcessAsync(document, supportsCodeGeneration, cancellationToken).ConfigureAwait(false); return items; } protected static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, Func<SyntaxReference, TextSpan> computeFullSpan) { return GetSymbolLocation(solution, symbol, tree, computeFullSpan, symbol.DeclaringSyntaxReferences); } private static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, Func<SyntaxReference, TextSpan> computeFullSpan, ImmutableArray<SyntaxReference> allReferences) { if (allReferences.Length == 0) return null; // See if there are any references in the starting file. We always prefer those for any symbol we find. var referencesInCurrentFile = allReferences.WhereAsArray(r => r.SyntaxTree == tree); if (referencesInCurrentFile.Length > 0) { // the symbol had one or more declarations in this file. We want to include all those spans in what we // return so that if the use enters any of its spans we highlight it in the list. An example of having // multiple locations in the same file would be a a partial type with multiple parts in the same file. // If we're not able to find a narrower navigation location in this file though then just navigate to // the first reference itself. var navigationLocationSpan = symbol.Locations.FirstOrDefault(loc => loc.SourceTree == tree)?.SourceSpan ?? referencesInCurrentFile.First().Span; var spans = referencesInCurrentFile.SelectAsArray(r => computeFullSpan(r)); return new SymbolItemLocation((spans, navigationLocationSpan), otherDocumentInfo: null); } else { // the symbol was defined in another file altogether. We don't care about it's full span // (since that is only needed for intersecting with the caret. Instead, we just need a // reasonable location to navigate them to. First try to find a narrow location to navigate to. // And, if we can't, just go to the first reference we can find. var navigationLocation = symbol.Locations.FirstOrDefault(loc => loc.SourceTree != null && loc.SourceTree != tree) ?? Location.Create(allReferences.First().SyntaxTree, allReferences.First().Span); var documentId = solution.GetDocumentId(navigationLocation.SourceTree); if (documentId == null) return null; return new SymbolItemLocation(inDocumentInfo: null, (documentId, navigationLocation.SourceSpan)); } } protected static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, ISymbolDeclarationService symbolDeclarationService) { return GetSymbolLocation(solution, symbol, tree, r => r.GetSyntax().FullSpan, symbolDeclarationService.GetDeclarations(symbol)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract class AbstractNavigationBarItemService : INavigationBarItemService { protected abstract Task<ImmutableArray<RoslynNavigationBarItem>> GetItemsInCurrentProcessAsync(Document document, bool supportsCodeGeneration, CancellationToken cancellationToken); public async Task<ImmutableArray<RoslynNavigationBarItem>> GetItemsAsync(Document document, bool supportsCodeGeneration, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. We don't need the full solution synchronized over to the OOP // in order to get accurate navbar contents for this document. var result = await client.TryInvokeAsync<IRemoteNavigationBarItemService, ImmutableArray<SerializableNavigationBarItem>>( document.Project, (service, solutionInfo, cancellationToken) => service.GetItemsAsync(solutionInfo, document.Id, supportsCodeGeneration, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value.SelectAsArray(v => v.Rehydrate()) : ImmutableArray<RoslynNavigationBarItem>.Empty; } var items = await GetItemsInCurrentProcessAsync(document, supportsCodeGeneration, cancellationToken).ConfigureAwait(false); return items; } protected static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, Func<SyntaxReference, TextSpan> computeFullSpan) { return GetSymbolLocation(solution, symbol, tree, computeFullSpan, symbol.DeclaringSyntaxReferences); } private static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, Func<SyntaxReference, TextSpan> computeFullSpan, ImmutableArray<SyntaxReference> allReferences) { if (allReferences.Length == 0) return null; // See if there are any references in the starting file. We always prefer those for any symbol we find. var referencesInCurrentFile = allReferences.WhereAsArray(r => r.SyntaxTree == tree); if (referencesInCurrentFile.Length > 0) { // the symbol had one or more declarations in this file. We want to include all those spans in what we // return so that if the use enters any of its spans we highlight it in the list. An example of having // multiple locations in the same file would be a a partial type with multiple parts in the same file. // If we're not able to find a narrower navigation location in this file though then just navigate to // the first reference itself. var navigationLocationSpan = symbol.Locations.FirstOrDefault(loc => loc.SourceTree == tree)?.SourceSpan ?? referencesInCurrentFile.First().Span; var spans = referencesInCurrentFile.SelectAsArray(r => computeFullSpan(r)); return new SymbolItemLocation((spans, navigationLocationSpan), otherDocumentInfo: null); } else { // the symbol was defined in another file altogether. We don't care about it's full span // (since that is only needed for intersecting with the caret. Instead, we just need a // reasonable location to navigate them to. First try to find a narrow location to navigate to. // And, if we can't, just go to the first reference we can find. var navigationLocation = symbol.Locations.FirstOrDefault(loc => loc.SourceTree != null && loc.SourceTree != tree) ?? Location.Create(allReferences.First().SyntaxTree, allReferences.First().Span); var documentId = solution.GetDocumentId(navigationLocation.SourceTree); if (documentId == null) return null; return new SymbolItemLocation(inDocumentInfo: null, (documentId, navigationLocation.SourceSpan)); } } protected static SymbolItemLocation? GetSymbolLocation( Solution solution, ISymbol symbol, SyntaxTree tree, ISymbolDeclarationService symbolDeclarationService) { return GetSymbolLocation(solution, symbol, tree, r => r.GetSyntax().FullSpan, symbolDeclarationService.GetDeclarations(symbol)); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxKinds.cs
// Licensed to the .NET Foundation under one or more 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.LanguageServices { /// <summary> /// Provides a uniform view of SyntaxKinds over C# and VB for constructs they have /// in common. /// </summary> internal interface ISyntaxKinds { TSyntaxKind Convert<TSyntaxKind>(int kind) where TSyntaxKind : struct; #region trivia int ConflictMarkerTrivia { get; } int DisabledTextTrivia { get; } int EndOfLineTrivia { get; } int SkippedTokensTrivia { get; } int WhitespaceTrivia { get; } int SingleLineCommentTrivia { get; } /// <summary> /// Gets the syntax kind for a multi-line comment. /// </summary> /// <value> /// The raw syntax kind for a multi-line comment; otherwise, <see langword="null"/> if the language does not /// support multi-line comments. /// </value> int? MultiLineCommentTrivia { get; } #endregion #region keywords int AwaitKeyword { get; } int AsyncKeyword { get; } int GlobalKeyword { get; } int IfKeyword { get; } int? GlobalStatement { get; } #endregion #region literal tokens int CharacterLiteralToken { get; } int StringLiteralToken { get; } #endregion #region tokens int CloseBraceToken { get; } int ColonToken { get; } int DotToken { get; } int EndOfFileToken { get; } int HashToken { get; } int IdentifierToken { get; } int InterpolatedStringTextToken { get; } int QuestionToken { get; } #endregion #region names int GenericName { get; } int IdentifierName { get; } int QualifiedName { get; } #endregion #region types int TupleType { get; } #endregion #region literal expressions int CharacterLiteralExpression { get; } int DefaultLiteralExpression { get; } int FalseLiteralExpression { get; } int NullLiteralExpression { get; } int StringLiteralExpression { get; } int TrueLiteralExpression { get; } #endregion #region expressions int AnonymousObjectCreationExpression { get; } int AwaitExpression { get; } int BaseExpression { get; } int ConditionalAccessExpression { get; } int ConditionalExpression { get; } int InterpolatedStringExpression { get; } int InvocationExpression { get; } int LogicalAndExpression { get; } int LogicalOrExpression { get; } int LogicalNotExpression { get; } int ObjectCreationExpression { get; } int ParenthesizedExpression { get; } int QueryExpression { get; } int ReferenceEqualsExpression { get; } int ReferenceNotEqualsExpression { get; } int SimpleMemberAccessExpression { get; } int TernaryConditionalExpression { get; } int ThisExpression { get; } int TupleExpression { get; } #endregion #region statements int ExpressionStatement { get; } int ForEachStatement { get; } int LocalDeclarationStatement { get; } int LockStatement { get; } int ReturnStatement { get; } int UsingStatement { get; } #endregion #region members/declarations int Attribute { get; } int Parameter { get; } int TypeConstraint { get; } int VariableDeclarator { get; } int FieldDeclaration { get; } int IncompleteMember { get; } int TypeArgumentList { get; } int ParameterList { get; } #endregion #region clauses int EqualsValueClause { get; } #endregion #region other int Interpolation { get; } int InterpolatedStringText { get; } #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. namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Provides a uniform view of SyntaxKinds over C# and VB for constructs they have /// in common. /// </summary> internal interface ISyntaxKinds { TSyntaxKind Convert<TSyntaxKind>(int kind) where TSyntaxKind : struct; #region trivia int ConflictMarkerTrivia { get; } int DisabledTextTrivia { get; } int EndOfLineTrivia { get; } int SkippedTokensTrivia { get; } int WhitespaceTrivia { get; } int SingleLineCommentTrivia { get; } /// <summary> /// Gets the syntax kind for a multi-line comment. /// </summary> /// <value> /// The raw syntax kind for a multi-line comment; otherwise, <see langword="null"/> if the language does not /// support multi-line comments. /// </value> int? MultiLineCommentTrivia { get; } #endregion #region keywords int AwaitKeyword { get; } int AsyncKeyword { get; } int GlobalKeyword { get; } int IfKeyword { get; } int? GlobalStatement { get; } #endregion #region literal tokens int CharacterLiteralToken { get; } int StringLiteralToken { get; } #endregion #region tokens int CloseBraceToken { get; } int ColonToken { get; } int DotToken { get; } int EndOfFileToken { get; } int HashToken { get; } int IdentifierToken { get; } int InterpolatedStringTextToken { get; } int QuestionToken { get; } #endregion #region names int GenericName { get; } int IdentifierName { get; } int QualifiedName { get; } #endregion #region types int TupleType { get; } #endregion #region literal expressions int CharacterLiteralExpression { get; } int DefaultLiteralExpression { get; } int FalseLiteralExpression { get; } int NullLiteralExpression { get; } int StringLiteralExpression { get; } int TrueLiteralExpression { get; } #endregion #region expressions int AnonymousObjectCreationExpression { get; } int AwaitExpression { get; } int BaseExpression { get; } int ConditionalAccessExpression { get; } int ConditionalExpression { get; } int InterpolatedStringExpression { get; } int InvocationExpression { get; } int LogicalAndExpression { get; } int LogicalOrExpression { get; } int LogicalNotExpression { get; } int ObjectCreationExpression { get; } int ParenthesizedExpression { get; } int QueryExpression { get; } int ReferenceEqualsExpression { get; } int ReferenceNotEqualsExpression { get; } int SimpleMemberAccessExpression { get; } int TernaryConditionalExpression { get; } int ThisExpression { get; } int TupleExpression { get; } #endregion #region statements int ExpressionStatement { get; } int ForEachStatement { get; } int LocalDeclarationStatement { get; } int LockStatement { get; } int ReturnStatement { get; } int UsingStatement { get; } #endregion #region members/declarations int Attribute { get; } int Parameter { get; } int TypeConstraint { get; } int VariableDeclarator { get; } int FieldDeclaration { get; } int IncompleteMember { get; } int TypeArgumentList { get; } int ParameterList { get; } #endregion #region clauses int EqualsValueClause { get; } #endregion #region other int Interpolation { get; } int InterpolatedStringText { get; } #endregion } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/Core/Implementation/InlineRename/CommandHandlers/AbstractRenameCommandHandler_OpenLineAboveHandler.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<OpenLineAboveCommandArgs> { public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context) { HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) => { activeSession.Commit(); nextHandler(); }); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<OpenLineAboveCommandArgs> { public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context) { HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) => { activeSession.Commit(); nextHandler(); }); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/Core/Undo/ISourceTextUndoTransaction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> /// with a display string by which the IDE's undo stack UI refers to the transaction. /// </summary> internal interface ISourceTextUndoTransaction : IDisposable { /// <summary> /// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction. /// </summary> SourceText SourceText { get; } /// <summary> /// The display string by which the IDE's undo stack UI refers to the transaction. /// </summary> string Description { 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 System; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> /// with a display string by which the IDE's undo stack UI refers to the transaction. /// </summary> internal interface ISourceTextUndoTransaction : IDisposable { /// <summary> /// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction. /// </summary> SourceText SourceText { get; } /// <summary> /// The display string by which the IDE's undo stack UI refers to the transaction. /// </summary> string Description { get; } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/ExpressionEvaluator/CSharp/Source/ResultProvider/NetFX20/AssemblyInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable [assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v2.0")]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable [assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v2.0")]
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { /// <summary> /// Code action for adding an import when we find a symbol in source in either our /// starting project, or some other unreferenced project in the solution. If we /// find a source symbol in a different project, we'll also add a p2p reference when /// we apply the code action. /// </summary> private class ProjectSymbolReferenceCodeAction : SymbolReferenceCodeAction { public ProjectSymbolReferenceCodeAction( Document originalDocument, AddImportFixData fixData) : base(originalDocument, fixData) { Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.ProjectSymbol); } private bool ShouldAddProjectReference() => FixData.ProjectReferenceToAdd != null && FixData.ProjectReferenceToAdd != OriginalDocument.Project.Id; protected override Task<CodeActionOperation?> UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { if (!ShouldAddProjectReference()) { return SpecializedTasks.Null<CodeActionOperation>(); } var projectWithAddedReference = project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); var applyOperation = new ApplyChangesOperation(projectWithAddedReference.Solution); if (isPreview) { return Task.FromResult<CodeActionOperation?>(applyOperation); } return Task.FromResult<CodeActionOperation?>(new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation)); } private sealed class AddProjectReferenceCodeActionOperation : CodeActionOperation { private readonly ProjectId _referencingProject; private readonly ProjectId _referencedProject; private readonly ApplyChangesOperation _applyOperation; public AddProjectReferenceCodeActionOperation(ProjectId referencingProject, ProjectId referencedProject, ApplyChangesOperation applyOperation) { _referencingProject = referencingProject; _referencedProject = referencedProject; _applyOperation = applyOperation; } internal override bool ApplyDuringTests => true; public override void Apply(Workspace workspace, CancellationToken cancellationToken) { if (!CanApply(workspace)) return; _applyOperation.Apply(workspace, cancellationToken); } internal override bool TryApply(Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { if (!CanApply(workspace)) return false; return _applyOperation.TryApply(workspace, progressTracker, cancellationToken); } private bool CanApply(Workspace workspace) { return workspace.CanAddProjectReference(_referencingProject, _referencedProject); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { /// <summary> /// Code action for adding an import when we find a symbol in source in either our /// starting project, or some other unreferenced project in the solution. If we /// find a source symbol in a different project, we'll also add a p2p reference when /// we apply the code action. /// </summary> private class ProjectSymbolReferenceCodeAction : SymbolReferenceCodeAction { public ProjectSymbolReferenceCodeAction( Document originalDocument, AddImportFixData fixData) : base(originalDocument, fixData) { Contract.ThrowIfFalse(fixData.Kind == AddImportFixKind.ProjectSymbol); } private bool ShouldAddProjectReference() => FixData.ProjectReferenceToAdd != null && FixData.ProjectReferenceToAdd != OriginalDocument.Project.Id; protected override Task<CodeActionOperation?> UpdateProjectAsync(Project project, bool isPreview, CancellationToken cancellationToken) { if (!ShouldAddProjectReference()) { return SpecializedTasks.Null<CodeActionOperation>(); } var projectWithAddedReference = project.AddProjectReference(new ProjectReference(FixData.ProjectReferenceToAdd)); var applyOperation = new ApplyChangesOperation(projectWithAddedReference.Solution); if (isPreview) { return Task.FromResult<CodeActionOperation?>(applyOperation); } return Task.FromResult<CodeActionOperation?>(new AddProjectReferenceCodeActionOperation(OriginalDocument.Project.Id, FixData.ProjectReferenceToAdd, applyOperation)); } private sealed class AddProjectReferenceCodeActionOperation : CodeActionOperation { private readonly ProjectId _referencingProject; private readonly ProjectId _referencedProject; private readonly ApplyChangesOperation _applyOperation; public AddProjectReferenceCodeActionOperation(ProjectId referencingProject, ProjectId referencedProject, ApplyChangesOperation applyOperation) { _referencingProject = referencingProject; _referencedProject = referencedProject; _applyOperation = applyOperation; } internal override bool ApplyDuringTests => true; public override void Apply(Workspace workspace, CancellationToken cancellationToken) { if (!CanApply(workspace)) return; _applyOperation.Apply(workspace, cancellationToken); } internal override bool TryApply(Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { if (!CanApply(workspace)) return false; return _applyOperation.TryApply(workspace, progressTracker, cancellationToken); } private bool CanApply(Workspace workspace) { return workspace.CanAddProjectReference(_referencingProject, _referencedProject); } } } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingAssemblySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Essentially this is a wrapper around another AssemblySymbol that is responsible for retargeting /// symbols from one assembly to another. It can retarget symbols for multiple assemblies at the same time. /// /// 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.m_AssemblySymbol, but reference a special RetargetingAssemblySymbol created for /// C1 by ReferenceManager. /// /// Here is how retargeting is implemented in general: /// - Symbols from underlying assembly are substituted with retargeting symbols. /// - Symbols from referenced assemblies that can be reused as is (i.e. doesn't have to be retargeted) are /// used as is. /// - Symbols from referenced assemblies that must be retargeted are substituted with result of retargeting. /// </summary> internal sealed class RetargetingAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// The underlying AssemblySymbol, it leaks symbols that should be retargeted. /// This cannot be an instance of RetargetingAssemblySymbol. /// </summary> private readonly SourceAssemblySymbol _underlyingAssembly; /// <summary> /// The list of contained ModuleSymbol objects. First item in the list /// is RetargetingModuleSymbol that wraps corresponding SourceModuleSymbol /// from underlyingAssembly.Modules list, the rest are PEModuleSymbols for /// added modules. /// </summary> private readonly ImmutableArray<ModuleSymbol> _modules; /// <summary> /// An array of assemblies involved in canonical type resolution of /// NoPia local types defined within this assembly. In other words, all /// references used by a compilation referencing this assembly. /// The array and its content is provided by ReferenceManager and must not be modified. /// </summary> private ImmutableArray<AssemblySymbol> _noPiaResolutionAssemblies; /// <summary> /// An array of assemblies referenced by this assembly, which are linked (/l-ed) by /// each compilation that is using this AssemblySymbol as a reference. /// If this AssemblySymbol is linked too, it will be in this array too. /// The array and its content is provided by ReferenceManager and must not be modified. /// </summary> private ImmutableArray<AssemblySymbol> _linkedReferencedAssemblies; /// <summary> /// Backing field for the map from a local NoPia type to corresponding canonical type. /// </summary> private ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol> _noPiaUnificationMap; /// <summary> /// A map from a local NoPia type to corresponding canonical type. /// </summary> internal ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol> NoPiaUnificationMap => LazyInitializer.EnsureInitialized(ref _noPiaUnificationMap, () => new ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol>(concurrencyLevel: 2, capacity: 0)); /// <summary> /// Assembly is /l-ed by compilation that is using it as a reference. /// </summary> private readonly bool _isLinked; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; /// <summary> /// Constructor. /// </summary> /// <param name="underlyingAssembly"> /// The underlying AssemblySymbol, cannot be an instance of RetargetingAssemblySymbol. /// </param> /// <param name="isLinked"> /// Assembly is /l-ed by compilation that is using it as a reference. /// </param> public RetargetingAssemblySymbol(SourceAssemblySymbol underlyingAssembly, bool isLinked) { Debug.Assert((object)underlyingAssembly != null); _underlyingAssembly = underlyingAssembly; ModuleSymbol[] modules = new ModuleSymbol[underlyingAssembly.Modules.Length]; modules[0] = new RetargetingModuleSymbol(this, (SourceModuleSymbol)underlyingAssembly.Modules[0]); for (int i = 1; i < underlyingAssembly.Modules.Length; i++) { PEModuleSymbol under = (PEModuleSymbol)underlyingAssembly.Modules[i]; modules[i] = new PEModuleSymbol(this, under.Module, under.ImportOptions, i); } _modules = modules.AsImmutableOrNull(); _isLinked = isLinked; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return ((RetargetingModuleSymbol)_modules[0]).RetargetingTranslator; } } /// <summary> /// The underlying <see cref="SourceAssemblySymbol"/>. /// </summary> public SourceAssemblySymbol UnderlyingAssembly { get { return _underlyingAssembly; } } public override bool IsImplicitlyDeclared { get { return _underlyingAssembly.IsImplicitlyDeclared; } } public override AssemblyIdentity Identity { get { return _underlyingAssembly.Identity; } } public override Version AssemblyVersionPattern => _underlyingAssembly.AssemblyVersionPattern; internal override ImmutableArray<byte> PublicKey { get { return _underlyingAssembly.PublicKey; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingAssembly.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override ImmutableArray<ModuleSymbol> Modules { get { return _modules; } } internal override bool KeepLookingForDeclaredSpecialTypes { get { // RetargetingAssemblySymbol never represents Core library. return false; } } public override ImmutableArray<Location> Locations { get { return _underlyingAssembly.Locations; } } internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName) { return _underlyingAssembly.GetInternalsVisibleToPublicKeys(simpleName); } internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other) { return _underlyingAssembly.AreInternalsVisibleToThisAssembly(other); } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return RetargetingTranslator.GetRetargetedAttributes(_underlyingAssembly.GetAttributes(), ref _lazyCustomAttributes); } /// <summary> /// Lookup declaration for FX type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks></remarks> internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { // Cor library should not have any references and, therefore, should never be // wrapped by a RetargetingAssemblySymbol. throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies() { return _noPiaResolutionAssemblies; } internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies) { _noPiaResolutionAssemblies = assemblies; } internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies) { _linkedReferencedAssemblies = assemblies; } internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies() { return _linkedReferencedAssemblies; } internal override bool IsLinked { get { return _isLinked; } } public override ICollection<string> TypeNames { get { return _underlyingAssembly.TypeNames; } } public override ICollection<string> NamespaceNames { get { return _underlyingAssembly.NamespaceNames; } } public override bool MightContainExtensionMethods { get { return _underlyingAssembly.MightContainExtensionMethods; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal override bool GetGuidString(out string guidString) { return _underlyingAssembly.GetGuidString(out guidString); } internal override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { NamedTypeSymbol underlying = _underlyingAssembly.TryLookupForwardedMetadataType(ref emittedName); if ((object)underlying == null) { return null; } return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } internal override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes() { foreach (NamedTypeSymbol underlying in _underlyingAssembly.GetAllTopLevelForwardedTypes()) { yield return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } } public override AssemblyMetadata GetMetadata() => _underlyingAssembly.GetMetadata(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Essentially this is a wrapper around another AssemblySymbol that is responsible for retargeting /// symbols from one assembly to another. It can retarget symbols for multiple assemblies at the same time. /// /// 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.m_AssemblySymbol, but reference a special RetargetingAssemblySymbol created for /// C1 by ReferenceManager. /// /// Here is how retargeting is implemented in general: /// - Symbols from underlying assembly are substituted with retargeting symbols. /// - Symbols from referenced assemblies that can be reused as is (i.e. doesn't have to be retargeted) are /// used as is. /// - Symbols from referenced assemblies that must be retargeted are substituted with result of retargeting. /// </summary> internal sealed class RetargetingAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// The underlying AssemblySymbol, it leaks symbols that should be retargeted. /// This cannot be an instance of RetargetingAssemblySymbol. /// </summary> private readonly SourceAssemblySymbol _underlyingAssembly; /// <summary> /// The list of contained ModuleSymbol objects. First item in the list /// is RetargetingModuleSymbol that wraps corresponding SourceModuleSymbol /// from underlyingAssembly.Modules list, the rest are PEModuleSymbols for /// added modules. /// </summary> private readonly ImmutableArray<ModuleSymbol> _modules; /// <summary> /// An array of assemblies involved in canonical type resolution of /// NoPia local types defined within this assembly. In other words, all /// references used by a compilation referencing this assembly. /// The array and its content is provided by ReferenceManager and must not be modified. /// </summary> private ImmutableArray<AssemblySymbol> _noPiaResolutionAssemblies; /// <summary> /// An array of assemblies referenced by this assembly, which are linked (/l-ed) by /// each compilation that is using this AssemblySymbol as a reference. /// If this AssemblySymbol is linked too, it will be in this array too. /// The array and its content is provided by ReferenceManager and must not be modified. /// </summary> private ImmutableArray<AssemblySymbol> _linkedReferencedAssemblies; /// <summary> /// Backing field for the map from a local NoPia type to corresponding canonical type. /// </summary> private ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol> _noPiaUnificationMap; /// <summary> /// A map from a local NoPia type to corresponding canonical type. /// </summary> internal ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol> NoPiaUnificationMap => LazyInitializer.EnsureInitialized(ref _noPiaUnificationMap, () => new ConcurrentDictionary<NamedTypeSymbol, NamedTypeSymbol>(concurrencyLevel: 2, capacity: 0)); /// <summary> /// Assembly is /l-ed by compilation that is using it as a reference. /// </summary> private readonly bool _isLinked; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; /// <summary> /// Constructor. /// </summary> /// <param name="underlyingAssembly"> /// The underlying AssemblySymbol, cannot be an instance of RetargetingAssemblySymbol. /// </param> /// <param name="isLinked"> /// Assembly is /l-ed by compilation that is using it as a reference. /// </param> public RetargetingAssemblySymbol(SourceAssemblySymbol underlyingAssembly, bool isLinked) { Debug.Assert((object)underlyingAssembly != null); _underlyingAssembly = underlyingAssembly; ModuleSymbol[] modules = new ModuleSymbol[underlyingAssembly.Modules.Length]; modules[0] = new RetargetingModuleSymbol(this, (SourceModuleSymbol)underlyingAssembly.Modules[0]); for (int i = 1; i < underlyingAssembly.Modules.Length; i++) { PEModuleSymbol under = (PEModuleSymbol)underlyingAssembly.Modules[i]; modules[i] = new PEModuleSymbol(this, under.Module, under.ImportOptions, i); } _modules = modules.AsImmutableOrNull(); _isLinked = isLinked; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return ((RetargetingModuleSymbol)_modules[0]).RetargetingTranslator; } } /// <summary> /// The underlying <see cref="SourceAssemblySymbol"/>. /// </summary> public SourceAssemblySymbol UnderlyingAssembly { get { return _underlyingAssembly; } } public override bool IsImplicitlyDeclared { get { return _underlyingAssembly.IsImplicitlyDeclared; } } public override AssemblyIdentity Identity { get { return _underlyingAssembly.Identity; } } public override Version AssemblyVersionPattern => _underlyingAssembly.AssemblyVersionPattern; internal override ImmutableArray<byte> PublicKey { get { return _underlyingAssembly.PublicKey; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingAssembly.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override ImmutableArray<ModuleSymbol> Modules { get { return _modules; } } internal override bool KeepLookingForDeclaredSpecialTypes { get { // RetargetingAssemblySymbol never represents Core library. return false; } } public override ImmutableArray<Location> Locations { get { return _underlyingAssembly.Locations; } } internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName) { return _underlyingAssembly.GetInternalsVisibleToPublicKeys(simpleName); } internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other) { return _underlyingAssembly.AreInternalsVisibleToThisAssembly(other); } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return RetargetingTranslator.GetRetargetedAttributes(_underlyingAssembly.GetAttributes(), ref _lazyCustomAttributes); } /// <summary> /// Lookup declaration for FX type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> /// <remarks></remarks> internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { // Cor library should not have any references and, therefore, should never be // wrapped by a RetargetingAssemblySymbol. throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies() { return _noPiaResolutionAssemblies; } internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies) { _noPiaResolutionAssemblies = assemblies; } internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies) { _linkedReferencedAssemblies = assemblies; } internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies() { return _linkedReferencedAssemblies; } internal override bool IsLinked { get { return _isLinked; } } public override ICollection<string> TypeNames { get { return _underlyingAssembly.TypeNames; } } public override ICollection<string> NamespaceNames { get { return _underlyingAssembly.NamespaceNames; } } public override bool MightContainExtensionMethods { get { return _underlyingAssembly.MightContainExtensionMethods; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal override bool GetGuidString(out string guidString) { return _underlyingAssembly.GetGuidString(out guidString); } internal override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { NamedTypeSymbol underlying = _underlyingAssembly.TryLookupForwardedMetadataType(ref emittedName); if ((object)underlying == null) { return null; } return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } internal override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes() { foreach (NamedTypeSymbol underlying in _underlyingAssembly.GetAllTopLevelForwardedTypes()) { yield return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } } public override AssemblyMetadata GetMetadata() => _underlyingAssembly.GetMetadata(); } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/CSharp/Portable/CodeCleanup/CSharpCodeCleanerServiceFactory.cs
// Licensed to the .NET Foundation under one or more 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.CodeCleanup; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { [ExportLanguageServiceFactory(typeof(ICodeCleanerService), LanguageNames.CSharp), Shared] internal class CSharpCodeCleanerServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanerServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeCleanerService(); } }
// Licensed to the .NET Foundation under one or more 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.CodeCleanup; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { [ExportLanguageServiceFactory(typeof(ICodeCleanerService), LanguageNames.CSharp), Shared] internal class CSharpCodeCleanerServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanerServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeCleanerService(); } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Portable/Symbols/PublicModel/ModuleSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ModuleSymbol : Symbol, IModuleSymbol { private readonly Symbols.ModuleSymbol _underlying; public ModuleSymbol(Symbols.ModuleSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceSymbol IModuleSymbol.GlobalNamespace { get { return _underlying.GlobalNamespace.GetPublicSymbol(); } } INamespaceSymbol IModuleSymbol.GetModuleNamespace(INamespaceSymbol namespaceSymbol) { return _underlying.GetModuleNamespace(namespaceSymbol).GetPublicSymbol(); } ImmutableArray<IAssemblySymbol> IModuleSymbol.ReferencedAssemblySymbols { get { return _underlying.ReferencedAssemblySymbols.GetPublicSymbols(); } } ImmutableArray<AssemblyIdentity> IModuleSymbol.ReferencedAssemblies => _underlying.ReferencedAssemblies; ModuleMetadata IModuleSymbol.GetMetadata() => _underlying.GetMetadata(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitModule(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitModule(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ModuleSymbol : Symbol, IModuleSymbol { private readonly Symbols.ModuleSymbol _underlying; public ModuleSymbol(Symbols.ModuleSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceSymbol IModuleSymbol.GlobalNamespace { get { return _underlying.GlobalNamespace.GetPublicSymbol(); } } INamespaceSymbol IModuleSymbol.GetModuleNamespace(INamespaceSymbol namespaceSymbol) { return _underlying.GetModuleNamespace(namespaceSymbol).GetPublicSymbol(); } ImmutableArray<IAssemblySymbol> IModuleSymbol.ReferencedAssemblySymbols { get { return _underlying.ReferencedAssemblySymbols.GetPublicSymbols(); } } ImmutableArray<AssemblyIdentity> IModuleSymbol.ReferencedAssemblies => _underlying.ReferencedAssemblies; ModuleMetadata IModuleSymbol.GetMetadata() => _underlying.GetMetadata(); #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitModule(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitModule(this); } #endregion } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Members.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SymbolDisplayVisitor { private const string IL_KEYWORD_MODOPT = "modopt"; private const string IL_KEYWORD_MODREQ = "modreq"; private void VisitFieldType(IFieldSymbol symbol) { symbol.Type.Accept(this.NotFirstVisitor); } public override void VisitField(IFieldSymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); AddFieldModifiersIfRequired(symbol); if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType) && this.isFirstSymbolVisited && !IsEnumMember(symbol)) { VisitFieldType(symbol); AddSpace(); AddCustomModifiersIfRequired(symbol.CustomModifiers); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } if (symbol.ContainingType.TypeKind == TypeKind.Enum) { builder.Add(CreatePart(SymbolDisplayPartKind.EnumMemberName, symbol, symbol.Name)); } else if (symbol.IsConst) { builder.Add(CreatePart(SymbolDisplayPartKind.ConstantName, symbol, symbol.Name)); } else { builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, symbol.Name)); } if (this.isFirstSymbolVisited && format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeConstantValue) && symbol.IsConst && symbol.HasConstantValue && CanAddConstant(symbol.Type, symbol.ConstantValue)) { AddSpace(); AddPunctuation(SyntaxKind.EqualsToken); AddSpace(); AddConstantValue(symbol.Type, symbol.ConstantValue, preferNumericValueOrExpandedFlagsForEnum: IsEnumMember(symbol)); } } private static bool ShouldPropertyDisplayReadOnly(IPropertySymbol property) { if (property.ContainingType?.IsReadOnly == true) { return false; } // If at least one accessor is present and all present accessors are readonly, the property should be marked readonly. var getMethod = property.GetMethod; if (getMethod is object && !ShouldMethodDisplayReadOnly(getMethod, property)) { return false; } var setMethod = property.SetMethod; if (setMethod is object && !ShouldMethodDisplayReadOnly(setMethod, property)) { return false; } return getMethod is object || setMethod is object; } private static bool ShouldMethodDisplayReadOnly(IMethodSymbol method, IPropertySymbol propertyOpt = null) { if (method.ContainingType?.IsReadOnly == true) { return false; } if ((method as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SourcePropertyAccessorSymbol sourceAccessor && (propertyOpt as Symbols.PublicModel.PropertySymbol)?.UnderlyingSymbol is SourcePropertySymbolBase sourceProperty) { // only display if the accessor is explicitly readonly return sourceAccessor.LocalDeclaredReadOnly || sourceProperty.HasReadOnlyModifier; } else if (method is Symbols.PublicModel.MethodSymbol m) { return m.UnderlyingMethodSymbol.IsDeclaredReadOnly; } return false; } public override void VisitProperty(IPropertySymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); if (ShouldPropertyDisplayReadOnly(symbol)) { AddReadOnlyIfRequired(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { if (symbol.ReturnsByRef) { AddRefIfRequired(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonlyIfRequired(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); symbol.Type.Accept(this.NotFirstVisitor); AddSpace(); AddCustomModifiersIfRequired(symbol.TypeCustomModifiers); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } AddPropertyNameAndParameters(symbol); if (format.PropertyStyle == SymbolDisplayPropertyStyle.ShowReadWriteDescriptor) { AddSpace(); AddPunctuation(SyntaxKind.OpenBraceToken); AddAccessor(symbol, symbol.GetMethod, SyntaxKind.GetKeyword); var keywordForSetAccessor = IsInitOnly(symbol.SetMethod) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword; AddAccessor(symbol, symbol.SetMethod, keywordForSetAccessor); AddSpace(); AddPunctuation(SyntaxKind.CloseBraceToken); } } private static bool IsInitOnly(IMethodSymbol symbol) { return symbol?.IsInitOnly == true; } private void AddPropertyNameAndParameters(IPropertySymbol symbol) { bool getMemberNameWithoutInterfaceName = symbol.Name.LastIndexOf('.') > 0; if (getMemberNameWithoutInterfaceName) { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); } if (symbol.IsIndexer) { AddKeyword(SyntaxKind.ThisKeyword); } else if (getMemberNameWithoutInterfaceName) { this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); } else { this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, symbol.Name)); } if (this.format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters) && symbol.Parameters.Any()) { AddPunctuation(SyntaxKind.OpenBracketToken); AddParametersIfRequired(hasThisParameter: false, isVarargs: false, parameters: symbol.Parameters); AddPunctuation(SyntaxKind.CloseBracketToken); } } public override void VisitEvent(IEventSymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); var accessor = symbol.AddMethod ?? symbol.RemoveMethod; if (accessor is object && ShouldMethodDisplayReadOnly(accessor)) { AddReadOnlyIfRequired(); } if (format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeMemberKeyword)) { AddKeyword(SyntaxKind.EventKeyword); AddSpace(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { symbol.Type.Accept(this.NotFirstVisitor); AddSpace(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } AddEventName(symbol); } private void AddEventName(IEventSymbol symbol) { if (symbol.Name.LastIndexOf('.') > 0) { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); } else { this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, symbol.Name)); } } public override void VisitMethod(IMethodSymbol symbol) { if (symbol.MethodKind == MethodKind.AnonymousFunction) { // TODO(cyrusn): Why is this a literal? Why don't we give the appropriate signature // of the method as asked? builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, "lambda expression")); return; } else if ((symbol as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SynthesizedGlobalMethodSymbol) // It would be nice to handle VB symbols too, but it's not worth the effort. { // Represents a compiler generated synthesized method symbol with a null containing // type. // TODO(cyrusn); Why is this a literal? builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, symbol.Name)); return; } else if (symbol.MethodKind == MethodKind.FunctionPointerSignature) { visitFunctionPointerSignature(symbol); return; } if (symbol.IsExtensionMethod && format.ExtensionMethodStyle != SymbolDisplayExtensionMethodStyle.Default) { if (symbol.MethodKind == MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.StaticMethod) { symbol = symbol.GetConstructedReducedFrom(); } else if (symbol.MethodKind != MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.InstanceMethod) { // If we cannot reduce this to an instance form then display in the static form symbol = symbol.ReduceExtensionMethod(symbol.Parameters.First().Type) ?? symbol; } } // Method members always have a type unless (1) this is a lambda method symbol, which we // have dealt with already, or (2) this is an error method symbol. If we have an error method // symbol then we do not know its accessibility, modifiers, etc, all of which require knowing // the containing type, so we'll skip them. if ((object)symbol.ContainingType != null || (symbol.ContainingSymbol is ITypeSymbol)) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); if (ShouldMethodDisplayReadOnly(symbol)) { AddReadOnlyIfRequired(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { switch (symbol.MethodKind) { case MethodKind.Constructor: case MethodKind.StaticConstructor: break; case MethodKind.Destructor: case MethodKind.Conversion: // If we're using the metadata format, then include the return type. // Otherwise we eschew it since it is redundant in a conversion // signature. if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { goto default; } break; default: // The display code is called by the debugger; if a developer is debugging Roslyn and attempts // to visualize a symbol *during its construction*, the parameters and return type might // still be null. if (symbol.ReturnsByRef) { AddRefIfRequired(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonlyIfRequired(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); if (symbol.ReturnsVoid) { AddKeyword(SyntaxKind.VoidKeyword); } else if (symbol.ReturnType != null) { AddReturnType(symbol); } AddSpace(); AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers); break; } } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType)) { ITypeSymbol containingType; bool includeType; if (symbol.MethodKind == MethodKind.LocalFunction) { includeType = false; containingType = null; } else if (symbol.MethodKind == MethodKind.ReducedExtension) { containingType = symbol.ReceiverType; includeType = true; Debug.Assert(containingType != null); } else { containingType = symbol.ContainingType; if ((object)containingType != null) { includeType = IncludeNamedType(symbol.ContainingType); } else { containingType = (ITypeSymbol)symbol.ContainingSymbol; includeType = true; } } if (includeType) { containingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } } } bool isAccessor = false; switch (symbol.MethodKind) { case MethodKind.Ordinary: case MethodKind.DelegateInvoke: case MethodKind.LocalFunction: { //containing type will be the delegate type, name will be Invoke builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name)); break; } case MethodKind.ReducedExtension: { // Note: Extension methods invoked off of their static class will be tagged as methods. // This behavior matches the semantic classification done in NameSyntaxClassifier. builder.Add(CreatePart(SymbolDisplayPartKind.ExtensionMethodName, symbol, symbol.Name)); break; } case MethodKind.PropertyGet: case MethodKind.PropertySet: { isAccessor = true; var associatedProperty = (IPropertySymbol)symbol.AssociatedSymbol; if (associatedProperty == null) { goto case MethodKind.Ordinary; } AddPropertyNameAndParameters(associatedProperty); AddPunctuation(SyntaxKind.DotToken); AddKeyword(symbol.MethodKind == MethodKind.PropertyGet ? SyntaxKind.GetKeyword : IsInitOnly(symbol) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword); break; } case MethodKind.EventAdd: case MethodKind.EventRemove: { isAccessor = true; var associatedEvent = (IEventSymbol)symbol.AssociatedSymbol; if (associatedEvent == null) { goto case MethodKind.Ordinary; } AddEventName(associatedEvent); AddPunctuation(SyntaxKind.DotToken); AddKeyword(symbol.MethodKind == MethodKind.EventAdd ? SyntaxKind.AddKeyword : SyntaxKind.RemoveKeyword); break; } case MethodKind.Constructor: case MethodKind.StaticConstructor: { // Note: we are using the metadata name also in the case that // symbol.containingType is null (which should never be the case here) or is an // anonymous type (which 'does not have a name'). var name = format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null || symbol.ContainingType.IsAnonymousType ? symbol.Name : symbol.ContainingType.Name; var partKind = GetPartKindForConstructorOrDestructor(symbol); builder.Add(CreatePart(partKind, symbol, name)); break; } case MethodKind.Destructor: { var partKind = GetPartKindForConstructorOrDestructor(symbol); // Note: we are using the metadata name also in the case that symbol.containingType is null, which should never be the case here. if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null) { builder.Add(CreatePart(partKind, symbol, symbol.Name)); } else { AddPunctuation(SyntaxKind.TildeToken); builder.Add(CreatePart(partKind, symbol, symbol.ContainingType.Name)); } break; } case MethodKind.ExplicitInterfaceImplementation: { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); if (!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) && symbol.GetSymbol()?.OriginalDefinition is SourceUserDefinedOperatorSymbolBase sourceUserDefinedOperatorSymbolBase) { var operatorName = symbol.MetadataName; var lastDotPosition = operatorName.LastIndexOf('.'); if (lastDotPosition >= 0) { operatorName = operatorName.Substring(lastDotPosition + 1); } if (sourceUserDefinedOperatorSymbolBase is SourceUserDefinedConversionSymbol) { addUserDefinedConversionName(symbol, operatorName); } else { addUserDefinedOperatorName(symbol, operatorName); } break; } builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); break; } case MethodKind.UserDefinedOperator: case MethodKind.BuiltinOperator: { if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName)); } else { addUserDefinedOperatorName(symbol, symbol.MetadataName); } break; } case MethodKind.Conversion: { if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName)); } else { addUserDefinedConversionName(symbol, symbol.MetadataName); } break; } default: throw ExceptionUtilities.UnexpectedValue(symbol.MethodKind); } if (!isAccessor) { AddTypeArguments(symbol, default(ImmutableArray<ImmutableArray<CustomModifier>>)); AddParameters(symbol); AddTypeParameterConstraints(symbol); } void visitFunctionPointerSignature(IMethodSymbol symbol) { AddKeyword(SyntaxKind.DelegateKeyword); AddPunctuation(SyntaxKind.AsteriskToken); if (symbol.CallingConvention != SignatureCallingConvention.Default) { AddSpace(); AddKeyword(SyntaxKind.UnmanagedKeyword); var conventionTypes = symbol.UnmanagedCallingConventionTypes; if (symbol.CallingConvention != SignatureCallingConvention.Unmanaged || !conventionTypes.IsEmpty) { AddPunctuation(SyntaxKind.OpenBracketToken); switch (symbol.CallingConvention) { case SignatureCallingConvention.CDecl: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Cdecl")); break; case SignatureCallingConvention.StdCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Stdcall")); break; case SignatureCallingConvention.ThisCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Thiscall")); break; case SignatureCallingConvention.FastCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Fastcall")); break; case SignatureCallingConvention.Unmanaged: Debug.Assert(!conventionTypes.IsDefaultOrEmpty); bool isFirst = true; foreach (var conventionType in conventionTypes) { if (!isFirst) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } isFirst = false; Debug.Assert(conventionType.Name.StartsWith("CallConv")); const int CallConvLength = 8; builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, conventionType, conventionType.Name[CallConvLength..])); } break; } AddPunctuation(SyntaxKind.CloseBracketToken); } } AddPunctuation(SyntaxKind.LessThanToken); foreach (var param in symbol.Parameters) { AddParameterRefKind(param.RefKind); AddCustomModifiersIfRequired(param.RefCustomModifiers); param.Type.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(param.CustomModifiers, leadingSpace: true, trailingSpace: false); AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } if (symbol.ReturnsByRef) { AddRef(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonly(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); symbol.ReturnType.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers, leadingSpace: true, trailingSpace: false); AddPunctuation(SyntaxKind.GreaterThanToken); } void addUserDefinedOperatorName(IMethodSymbol symbol, string operatorName) { AddKeyword(SyntaxKind.OperatorKeyword); AddSpace(); if (operatorName == WellKnownMemberNames.TrueOperatorName) { AddKeyword(SyntaxKind.TrueKeyword); } else if (operatorName == WellKnownMemberNames.FalseOperatorName) { AddKeyword(SyntaxKind.FalseKeyword); } else { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName)))); } } void addUserDefinedConversionName(IMethodSymbol symbol, string operatorName) { // "System.IntPtr.explicit operator System.IntPtr(int)" if (operatorName == WellKnownMemberNames.ExplicitConversionName) { AddKeyword(SyntaxKind.ExplicitKeyword); } else if (operatorName == WellKnownMemberNames.ImplicitConversionName) { AddKeyword(SyntaxKind.ImplicitKeyword); } else { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName)))); } AddSpace(); AddKeyword(SyntaxKind.OperatorKeyword); AddSpace(); AddReturnType(symbol); } } private static SymbolDisplayPartKind GetPartKindForConstructorOrDestructor(IMethodSymbol symbol) { // In the case that symbol.containingType is null (which should never be the case here) we will fallback to the MethodName symbol part if (symbol.ContainingType is null) { return SymbolDisplayPartKind.MethodName; } return GetPartKind(symbol.ContainingType); } private void AddReturnType(IMethodSymbol symbol) { symbol.ReturnType.Accept(this.NotFirstVisitor); } private void AddTypeParameterConstraints(IMethodSymbol symbol) { if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints)) { AddTypeParameterConstraints(symbol.TypeArguments); } } private void AddParameters(IMethodSymbol symbol) { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters)) { AddPunctuation(SyntaxKind.OpenParenToken); AddParametersIfRequired( hasThisParameter: symbol.IsExtensionMethod && symbol.MethodKind != MethodKind.ReducedExtension, isVarargs: symbol.IsVararg, parameters: symbol.Parameters); AddPunctuation(SyntaxKind.CloseParenToken); } } public override void VisitParameter(IParameterSymbol symbol) { // Note the asymmetry between VisitParameter and VisitTypeParameter: VisitParameter // decorates the parameter, whereas VisitTypeParameter leaves that to the corresponding // type or method. This is because type parameters are frequently used in other contexts // (e.g. field types, param types, etc), which just want the name whereas parameters are // used on their own or in the context of methods. var includeType = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeType); var includeName = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) && symbol.Name.Length != 0; var includeBrackets = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeOptionalBrackets); var includeDefaultValue = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeDefaultValue) && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) && symbol.HasExplicitDefaultValue && CanAddConstant(symbol.Type, symbol.ExplicitDefaultValue); if (includeBrackets && symbol.IsOptional) { AddPunctuation(SyntaxKind.OpenBracketToken); } if (includeType) { AddParameterRefKindIfRequired(symbol.RefKind); AddCustomModifiersIfRequired(symbol.RefCustomModifiers, leadingSpace: false, trailingSpace: true); if (symbol.IsParams && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut)) { AddKeyword(SyntaxKind.ParamsKeyword); AddSpace(); } symbol.Type.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true, trailingSpace: false); } if (includeName) { if (includeType) { AddSpace(); } var kind = symbol.IsThis ? SymbolDisplayPartKind.Keyword : SymbolDisplayPartKind.ParameterName; builder.Add(CreatePart(kind, symbol, symbol.Name)); } if (includeDefaultValue) { if (includeName || includeType) { AddSpace(); } AddPunctuation(SyntaxKind.EqualsToken); AddSpace(); AddConstantValue(symbol.Type, symbol.ExplicitDefaultValue); } if (includeBrackets && symbol.IsOptional) { AddPunctuation(SyntaxKind.CloseBracketToken); } } private static bool CanAddConstant(ITypeSymbol type, object value) { if (type.TypeKind == TypeKind.Enum) { return true; } if (value == null) { return true; } return value.GetType().GetTypeInfo().IsPrimitive || value is string || value is decimal; } private void AddFieldModifiersIfRequired(IFieldSymbol symbol) { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) && !IsEnumMember(symbol)) { if (symbol.IsConst) { AddKeyword(SyntaxKind.ConstKeyword); AddSpace(); } if (symbol.IsReadOnly) { AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } if (symbol.IsVolatile) { AddKeyword(SyntaxKind.VolatileKeyword); AddSpace(); } //TODO: event } } private void AddMemberModifiersIfRequired(ISymbol symbol) { INamedTypeSymbol containingType = symbol.ContainingType; // all members (that end up here) must have a containing type or a containing symbol should be a TypeSymbol. Debug.Assert(containingType != null || (symbol.ContainingSymbol is ITypeSymbol)); if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) && (containingType == null || (containingType.TypeKind != TypeKind.Interface && !IsEnumMember(symbol) && !IsLocalFunction(symbol)))) { var isConst = symbol is IFieldSymbol && ((IFieldSymbol)symbol).IsConst; if (symbol.IsStatic && !isConst) { AddKeyword(SyntaxKind.StaticKeyword); AddSpace(); } if (symbol.IsOverride) { AddKeyword(SyntaxKind.OverrideKeyword); AddSpace(); } if (symbol.IsAbstract) { AddKeyword(SyntaxKind.AbstractKeyword); AddSpace(); } if (symbol.IsSealed) { AddKeyword(SyntaxKind.SealedKeyword); AddSpace(); } if (symbol.IsExtern) { AddKeyword(SyntaxKind.ExternKeyword); AddSpace(); } if (symbol.IsVirtual) { AddKeyword(SyntaxKind.VirtualKeyword); AddSpace(); } } } private void AddParametersIfRequired(bool hasThisParameter, bool isVarargs, ImmutableArray<IParameterSymbol> parameters) { if (format.ParameterOptions == SymbolDisplayParameterOptions.None) { return; } var first = true; // The display code is called by the debugger; if a developer is debugging Roslyn and attempts // to visualize a symbol *during its construction*, the parameters and return type might // still be null. if (!parameters.IsDefault) { foreach (var param in parameters) { if (!first) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } else if (hasThisParameter) { if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeExtensionThis)) { AddKeyword(SyntaxKind.ThisKeyword); AddSpace(); } } first = false; param.Accept(this.NotFirstVisitor); } } if (isVarargs) { if (!first) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } AddKeyword(SyntaxKind.ArgListKeyword); } } private void AddAccessor(IPropertySymbol property, IMethodSymbol method, SyntaxKind keyword) { if (method != null) { AddSpace(); if (method.DeclaredAccessibility != property.DeclaredAccessibility) { AddAccessibility(method); } if (!ShouldPropertyDisplayReadOnly(property) && ShouldMethodDisplayReadOnly(method, property)) { AddReadOnlyIfRequired(); } AddKeyword(keyword); AddPunctuation(SyntaxKind.SemicolonToken); } } private void AddExplicitInterfaceIfRequired<T>(ImmutableArray<T> implementedMembers) where T : ISymbol { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeExplicitInterface) && !implementedMembers.IsEmpty) { var implementedMember = implementedMembers[0]; Debug.Assert(implementedMember.ContainingType != null); INamedTypeSymbol containingType = implementedMember.ContainingType; if (containingType != null) { containingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } } } private void AddCustomModifiersIfRequired(ImmutableArray<CustomModifier> customModifiers, bool leadingSpace = false, bool trailingSpace = true) { if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers) && !customModifiers.IsEmpty) { bool first = true; foreach (CustomModifier customModifier in customModifiers) { if (!first || leadingSpace) { AddSpace(); } first = false; this.builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, null, customModifier.IsOptional ? IL_KEYWORD_MODOPT : IL_KEYWORD_MODREQ)); AddPunctuation(SyntaxKind.OpenParenToken); customModifier.Modifier.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.CloseParenToken); } if (trailingSpace) { AddSpace(); } } } private void AddRefIfRequired() { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddRef(); } } private void AddRef() { AddKeyword(SyntaxKind.RefKeyword); AddSpace(); } private void AddRefReadonlyIfRequired() { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddRefReadonly(); } } private void AddRefReadonly() { AddKeyword(SyntaxKind.RefKeyword); AddSpace(); AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } private void AddReadOnlyIfRequired() { // 'readonly' in this context is effectively a 'ref' modifier // because it affects whether the 'this' parameter is 'ref' or 'in'. if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } } private void AddParameterRefKindIfRequired(RefKind refKind) { if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut)) { AddParameterRefKind(refKind); } } private void AddParameterRefKind(RefKind refKind) { switch (refKind) { case RefKind.Out: AddKeyword(SyntaxKind.OutKeyword); AddSpace(); break; case RefKind.Ref: AddKeyword(SyntaxKind.RefKeyword); AddSpace(); break; case RefKind.In: AddKeyword(SyntaxKind.InKeyword); AddSpace(); break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SymbolDisplayVisitor { private const string IL_KEYWORD_MODOPT = "modopt"; private const string IL_KEYWORD_MODREQ = "modreq"; private void VisitFieldType(IFieldSymbol symbol) { symbol.Type.Accept(this.NotFirstVisitor); } public override void VisitField(IFieldSymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); AddFieldModifiersIfRequired(symbol); if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType) && this.isFirstSymbolVisited && !IsEnumMember(symbol)) { VisitFieldType(symbol); AddSpace(); AddCustomModifiersIfRequired(symbol.CustomModifiers); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } if (symbol.ContainingType.TypeKind == TypeKind.Enum) { builder.Add(CreatePart(SymbolDisplayPartKind.EnumMemberName, symbol, symbol.Name)); } else if (symbol.IsConst) { builder.Add(CreatePart(SymbolDisplayPartKind.ConstantName, symbol, symbol.Name)); } else { builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, symbol.Name)); } if (this.isFirstSymbolVisited && format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeConstantValue) && symbol.IsConst && symbol.HasConstantValue && CanAddConstant(symbol.Type, symbol.ConstantValue)) { AddSpace(); AddPunctuation(SyntaxKind.EqualsToken); AddSpace(); AddConstantValue(symbol.Type, symbol.ConstantValue, preferNumericValueOrExpandedFlagsForEnum: IsEnumMember(symbol)); } } private static bool ShouldPropertyDisplayReadOnly(IPropertySymbol property) { if (property.ContainingType?.IsReadOnly == true) { return false; } // If at least one accessor is present and all present accessors are readonly, the property should be marked readonly. var getMethod = property.GetMethod; if (getMethod is object && !ShouldMethodDisplayReadOnly(getMethod, property)) { return false; } var setMethod = property.SetMethod; if (setMethod is object && !ShouldMethodDisplayReadOnly(setMethod, property)) { return false; } return getMethod is object || setMethod is object; } private static bool ShouldMethodDisplayReadOnly(IMethodSymbol method, IPropertySymbol propertyOpt = null) { if (method.ContainingType?.IsReadOnly == true) { return false; } if ((method as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SourcePropertyAccessorSymbol sourceAccessor && (propertyOpt as Symbols.PublicModel.PropertySymbol)?.UnderlyingSymbol is SourcePropertySymbolBase sourceProperty) { // only display if the accessor is explicitly readonly return sourceAccessor.LocalDeclaredReadOnly || sourceProperty.HasReadOnlyModifier; } else if (method is Symbols.PublicModel.MethodSymbol m) { return m.UnderlyingMethodSymbol.IsDeclaredReadOnly; } return false; } public override void VisitProperty(IPropertySymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); if (ShouldPropertyDisplayReadOnly(symbol)) { AddReadOnlyIfRequired(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { if (symbol.ReturnsByRef) { AddRefIfRequired(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonlyIfRequired(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); symbol.Type.Accept(this.NotFirstVisitor); AddSpace(); AddCustomModifiersIfRequired(symbol.TypeCustomModifiers); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } AddPropertyNameAndParameters(symbol); if (format.PropertyStyle == SymbolDisplayPropertyStyle.ShowReadWriteDescriptor) { AddSpace(); AddPunctuation(SyntaxKind.OpenBraceToken); AddAccessor(symbol, symbol.GetMethod, SyntaxKind.GetKeyword); var keywordForSetAccessor = IsInitOnly(symbol.SetMethod) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword; AddAccessor(symbol, symbol.SetMethod, keywordForSetAccessor); AddSpace(); AddPunctuation(SyntaxKind.CloseBraceToken); } } private static bool IsInitOnly(IMethodSymbol symbol) { return symbol?.IsInitOnly == true; } private void AddPropertyNameAndParameters(IPropertySymbol symbol) { bool getMemberNameWithoutInterfaceName = symbol.Name.LastIndexOf('.') > 0; if (getMemberNameWithoutInterfaceName) { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); } if (symbol.IsIndexer) { AddKeyword(SyntaxKind.ThisKeyword); } else if (getMemberNameWithoutInterfaceName) { this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); } else { this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, symbol.Name)); } if (this.format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters) && symbol.Parameters.Any()) { AddPunctuation(SyntaxKind.OpenBracketToken); AddParametersIfRequired(hasThisParameter: false, isVarargs: false, parameters: symbol.Parameters); AddPunctuation(SyntaxKind.CloseBracketToken); } } public override void VisitEvent(IEventSymbol symbol) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); var accessor = symbol.AddMethod ?? symbol.RemoveMethod; if (accessor is object && ShouldMethodDisplayReadOnly(accessor)) { AddReadOnlyIfRequired(); } if (format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeMemberKeyword)) { AddKeyword(SyntaxKind.EventKeyword); AddSpace(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { symbol.Type.Accept(this.NotFirstVisitor); AddSpace(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) && IncludeNamedType(symbol.ContainingType)) { symbol.ContainingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } AddEventName(symbol); } private void AddEventName(IEventSymbol symbol) { if (symbol.Name.LastIndexOf('.') > 0) { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); } else { this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, symbol.Name)); } } public override void VisitMethod(IMethodSymbol symbol) { if (symbol.MethodKind == MethodKind.AnonymousFunction) { // TODO(cyrusn): Why is this a literal? Why don't we give the appropriate signature // of the method as asked? builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, "lambda expression")); return; } else if ((symbol as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SynthesizedGlobalMethodSymbol) // It would be nice to handle VB symbols too, but it's not worth the effort. { // Represents a compiler generated synthesized method symbol with a null containing // type. // TODO(cyrusn); Why is this a literal? builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, symbol.Name)); return; } else if (symbol.MethodKind == MethodKind.FunctionPointerSignature) { visitFunctionPointerSignature(symbol); return; } if (symbol.IsExtensionMethod && format.ExtensionMethodStyle != SymbolDisplayExtensionMethodStyle.Default) { if (symbol.MethodKind == MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.StaticMethod) { symbol = symbol.GetConstructedReducedFrom(); } else if (symbol.MethodKind != MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.InstanceMethod) { // If we cannot reduce this to an instance form then display in the static form symbol = symbol.ReduceExtensionMethod(symbol.Parameters.First().Type) ?? symbol; } } // Method members always have a type unless (1) this is a lambda method symbol, which we // have dealt with already, or (2) this is an error method symbol. If we have an error method // symbol then we do not know its accessibility, modifiers, etc, all of which require knowing // the containing type, so we'll skip them. if ((object)symbol.ContainingType != null || (symbol.ContainingSymbol is ITypeSymbol)) { AddAccessibilityIfRequired(symbol); AddMemberModifiersIfRequired(symbol); if (ShouldMethodDisplayReadOnly(symbol)) { AddReadOnlyIfRequired(); } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType)) { switch (symbol.MethodKind) { case MethodKind.Constructor: case MethodKind.StaticConstructor: break; case MethodKind.Destructor: case MethodKind.Conversion: // If we're using the metadata format, then include the return type. // Otherwise we eschew it since it is redundant in a conversion // signature. if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { goto default; } break; default: // The display code is called by the debugger; if a developer is debugging Roslyn and attempts // to visualize a symbol *during its construction*, the parameters and return type might // still be null. if (symbol.ReturnsByRef) { AddRefIfRequired(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonlyIfRequired(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); if (symbol.ReturnsVoid) { AddKeyword(SyntaxKind.VoidKeyword); } else if (symbol.ReturnType != null) { AddReturnType(symbol); } AddSpace(); AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers); break; } } if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType)) { ITypeSymbol containingType; bool includeType; if (symbol.MethodKind == MethodKind.LocalFunction) { includeType = false; containingType = null; } else if (symbol.MethodKind == MethodKind.ReducedExtension) { containingType = symbol.ReceiverType; includeType = true; Debug.Assert(containingType != null); } else { containingType = symbol.ContainingType; if ((object)containingType != null) { includeType = IncludeNamedType(symbol.ContainingType); } else { containingType = (ITypeSymbol)symbol.ContainingSymbol; includeType = true; } } if (includeType) { containingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } } } bool isAccessor = false; switch (symbol.MethodKind) { case MethodKind.Ordinary: case MethodKind.DelegateInvoke: case MethodKind.LocalFunction: { //containing type will be the delegate type, name will be Invoke builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name)); break; } case MethodKind.ReducedExtension: { // Note: Extension methods invoked off of their static class will be tagged as methods. // This behavior matches the semantic classification done in NameSyntaxClassifier. builder.Add(CreatePart(SymbolDisplayPartKind.ExtensionMethodName, symbol, symbol.Name)); break; } case MethodKind.PropertyGet: case MethodKind.PropertySet: { isAccessor = true; var associatedProperty = (IPropertySymbol)symbol.AssociatedSymbol; if (associatedProperty == null) { goto case MethodKind.Ordinary; } AddPropertyNameAndParameters(associatedProperty); AddPunctuation(SyntaxKind.DotToken); AddKeyword(symbol.MethodKind == MethodKind.PropertyGet ? SyntaxKind.GetKeyword : IsInitOnly(symbol) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword); break; } case MethodKind.EventAdd: case MethodKind.EventRemove: { isAccessor = true; var associatedEvent = (IEventSymbol)symbol.AssociatedSymbol; if (associatedEvent == null) { goto case MethodKind.Ordinary; } AddEventName(associatedEvent); AddPunctuation(SyntaxKind.DotToken); AddKeyword(symbol.MethodKind == MethodKind.EventAdd ? SyntaxKind.AddKeyword : SyntaxKind.RemoveKeyword); break; } case MethodKind.Constructor: case MethodKind.StaticConstructor: { // Note: we are using the metadata name also in the case that // symbol.containingType is null (which should never be the case here) or is an // anonymous type (which 'does not have a name'). var name = format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null || symbol.ContainingType.IsAnonymousType ? symbol.Name : symbol.ContainingType.Name; var partKind = GetPartKindForConstructorOrDestructor(symbol); builder.Add(CreatePart(partKind, symbol, name)); break; } case MethodKind.Destructor: { var partKind = GetPartKindForConstructorOrDestructor(symbol); // Note: we are using the metadata name also in the case that symbol.containingType is null, which should never be the case here. if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null) { builder.Add(CreatePart(partKind, symbol, symbol.Name)); } else { AddPunctuation(SyntaxKind.TildeToken); builder.Add(CreatePart(partKind, symbol, symbol.ContainingType.Name)); } break; } case MethodKind.ExplicitInterfaceImplementation: { AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations); if (!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) && symbol.GetSymbol()?.OriginalDefinition is SourceUserDefinedOperatorSymbolBase sourceUserDefinedOperatorSymbolBase) { var operatorName = symbol.MetadataName; var lastDotPosition = operatorName.LastIndexOf('.'); if (lastDotPosition >= 0) { operatorName = operatorName.Substring(lastDotPosition + 1); } if (sourceUserDefinedOperatorSymbolBase is SourceUserDefinedConversionSymbol) { addUserDefinedConversionName(symbol, operatorName); } else { addUserDefinedOperatorName(symbol, operatorName); } break; } builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name))); break; } case MethodKind.UserDefinedOperator: case MethodKind.BuiltinOperator: { if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName)); } else { addUserDefinedOperatorName(symbol, symbol.MetadataName); } break; } case MethodKind.Conversion: { if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames)) { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName)); } else { addUserDefinedConversionName(symbol, symbol.MetadataName); } break; } default: throw ExceptionUtilities.UnexpectedValue(symbol.MethodKind); } if (!isAccessor) { AddTypeArguments(symbol, default(ImmutableArray<ImmutableArray<CustomModifier>>)); AddParameters(symbol); AddTypeParameterConstraints(symbol); } void visitFunctionPointerSignature(IMethodSymbol symbol) { AddKeyword(SyntaxKind.DelegateKeyword); AddPunctuation(SyntaxKind.AsteriskToken); if (symbol.CallingConvention != SignatureCallingConvention.Default) { AddSpace(); AddKeyword(SyntaxKind.UnmanagedKeyword); var conventionTypes = symbol.UnmanagedCallingConventionTypes; if (symbol.CallingConvention != SignatureCallingConvention.Unmanaged || !conventionTypes.IsEmpty) { AddPunctuation(SyntaxKind.OpenBracketToken); switch (symbol.CallingConvention) { case SignatureCallingConvention.CDecl: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Cdecl")); break; case SignatureCallingConvention.StdCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Stdcall")); break; case SignatureCallingConvention.ThisCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Thiscall")); break; case SignatureCallingConvention.FastCall: builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Fastcall")); break; case SignatureCallingConvention.Unmanaged: Debug.Assert(!conventionTypes.IsDefaultOrEmpty); bool isFirst = true; foreach (var conventionType in conventionTypes) { if (!isFirst) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } isFirst = false; Debug.Assert(conventionType.Name.StartsWith("CallConv")); const int CallConvLength = 8; builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, conventionType, conventionType.Name[CallConvLength..])); } break; } AddPunctuation(SyntaxKind.CloseBracketToken); } } AddPunctuation(SyntaxKind.LessThanToken); foreach (var param in symbol.Parameters) { AddParameterRefKind(param.RefKind); AddCustomModifiersIfRequired(param.RefCustomModifiers); param.Type.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(param.CustomModifiers, leadingSpace: true, trailingSpace: false); AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } if (symbol.ReturnsByRef) { AddRef(); } else if (symbol.ReturnsByRefReadonly) { AddRefReadonly(); } AddCustomModifiersIfRequired(symbol.RefCustomModifiers); symbol.ReturnType.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers, leadingSpace: true, trailingSpace: false); AddPunctuation(SyntaxKind.GreaterThanToken); } void addUserDefinedOperatorName(IMethodSymbol symbol, string operatorName) { AddKeyword(SyntaxKind.OperatorKeyword); AddSpace(); if (operatorName == WellKnownMemberNames.TrueOperatorName) { AddKeyword(SyntaxKind.TrueKeyword); } else if (operatorName == WellKnownMemberNames.FalseOperatorName) { AddKeyword(SyntaxKind.FalseKeyword); } else { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName)))); } } void addUserDefinedConversionName(IMethodSymbol symbol, string operatorName) { // "System.IntPtr.explicit operator System.IntPtr(int)" if (operatorName == WellKnownMemberNames.ExplicitConversionName) { AddKeyword(SyntaxKind.ExplicitKeyword); } else if (operatorName == WellKnownMemberNames.ImplicitConversionName) { AddKeyword(SyntaxKind.ImplicitKeyword); } else { builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName)))); } AddSpace(); AddKeyword(SyntaxKind.OperatorKeyword); AddSpace(); AddReturnType(symbol); } } private static SymbolDisplayPartKind GetPartKindForConstructorOrDestructor(IMethodSymbol symbol) { // In the case that symbol.containingType is null (which should never be the case here) we will fallback to the MethodName symbol part if (symbol.ContainingType is null) { return SymbolDisplayPartKind.MethodName; } return GetPartKind(symbol.ContainingType); } private void AddReturnType(IMethodSymbol symbol) { symbol.ReturnType.Accept(this.NotFirstVisitor); } private void AddTypeParameterConstraints(IMethodSymbol symbol) { if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints)) { AddTypeParameterConstraints(symbol.TypeArguments); } } private void AddParameters(IMethodSymbol symbol) { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters)) { AddPunctuation(SyntaxKind.OpenParenToken); AddParametersIfRequired( hasThisParameter: symbol.IsExtensionMethod && symbol.MethodKind != MethodKind.ReducedExtension, isVarargs: symbol.IsVararg, parameters: symbol.Parameters); AddPunctuation(SyntaxKind.CloseParenToken); } } public override void VisitParameter(IParameterSymbol symbol) { // Note the asymmetry between VisitParameter and VisitTypeParameter: VisitParameter // decorates the parameter, whereas VisitTypeParameter leaves that to the corresponding // type or method. This is because type parameters are frequently used in other contexts // (e.g. field types, param types, etc), which just want the name whereas parameters are // used on their own or in the context of methods. var includeType = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeType); var includeName = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) && symbol.Name.Length != 0; var includeBrackets = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeOptionalBrackets); var includeDefaultValue = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeDefaultValue) && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) && symbol.HasExplicitDefaultValue && CanAddConstant(symbol.Type, symbol.ExplicitDefaultValue); if (includeBrackets && symbol.IsOptional) { AddPunctuation(SyntaxKind.OpenBracketToken); } if (includeType) { AddParameterRefKindIfRequired(symbol.RefKind); AddCustomModifiersIfRequired(symbol.RefCustomModifiers, leadingSpace: false, trailingSpace: true); if (symbol.IsParams && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut)) { AddKeyword(SyntaxKind.ParamsKeyword); AddSpace(); } symbol.Type.Accept(this.NotFirstVisitor); AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true, trailingSpace: false); } if (includeName) { if (includeType) { AddSpace(); } var kind = symbol.IsThis ? SymbolDisplayPartKind.Keyword : SymbolDisplayPartKind.ParameterName; builder.Add(CreatePart(kind, symbol, symbol.Name)); } if (includeDefaultValue) { if (includeName || includeType) { AddSpace(); } AddPunctuation(SyntaxKind.EqualsToken); AddSpace(); AddConstantValue(symbol.Type, symbol.ExplicitDefaultValue); } if (includeBrackets && symbol.IsOptional) { AddPunctuation(SyntaxKind.CloseBracketToken); } } private static bool CanAddConstant(ITypeSymbol type, object value) { if (type.TypeKind == TypeKind.Enum) { return true; } if (value == null) { return true; } return value.GetType().GetTypeInfo().IsPrimitive || value is string || value is decimal; } private void AddFieldModifiersIfRequired(IFieldSymbol symbol) { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) && !IsEnumMember(symbol)) { if (symbol.IsConst) { AddKeyword(SyntaxKind.ConstKeyword); AddSpace(); } if (symbol.IsReadOnly) { AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } if (symbol.IsVolatile) { AddKeyword(SyntaxKind.VolatileKeyword); AddSpace(); } //TODO: event } } private void AddMemberModifiersIfRequired(ISymbol symbol) { INamedTypeSymbol containingType = symbol.ContainingType; // all members (that end up here) must have a containing type or a containing symbol should be a TypeSymbol. Debug.Assert(containingType != null || (symbol.ContainingSymbol is ITypeSymbol)); if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) && (containingType == null || (containingType.TypeKind != TypeKind.Interface && !IsEnumMember(symbol) && !IsLocalFunction(symbol)))) { var isConst = symbol is IFieldSymbol && ((IFieldSymbol)symbol).IsConst; if (symbol.IsStatic && !isConst) { AddKeyword(SyntaxKind.StaticKeyword); AddSpace(); } if (symbol.IsOverride) { AddKeyword(SyntaxKind.OverrideKeyword); AddSpace(); } if (symbol.IsAbstract) { AddKeyword(SyntaxKind.AbstractKeyword); AddSpace(); } if (symbol.IsSealed) { AddKeyword(SyntaxKind.SealedKeyword); AddSpace(); } if (symbol.IsExtern) { AddKeyword(SyntaxKind.ExternKeyword); AddSpace(); } if (symbol.IsVirtual) { AddKeyword(SyntaxKind.VirtualKeyword); AddSpace(); } } } private void AddParametersIfRequired(bool hasThisParameter, bool isVarargs, ImmutableArray<IParameterSymbol> parameters) { if (format.ParameterOptions == SymbolDisplayParameterOptions.None) { return; } var first = true; // The display code is called by the debugger; if a developer is debugging Roslyn and attempts // to visualize a symbol *during its construction*, the parameters and return type might // still be null. if (!parameters.IsDefault) { foreach (var param in parameters) { if (!first) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } else if (hasThisParameter) { if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeExtensionThis)) { AddKeyword(SyntaxKind.ThisKeyword); AddSpace(); } } first = false; param.Accept(this.NotFirstVisitor); } } if (isVarargs) { if (!first) { AddPunctuation(SyntaxKind.CommaToken); AddSpace(); } AddKeyword(SyntaxKind.ArgListKeyword); } } private void AddAccessor(IPropertySymbol property, IMethodSymbol method, SyntaxKind keyword) { if (method != null) { AddSpace(); if (method.DeclaredAccessibility != property.DeclaredAccessibility) { AddAccessibility(method); } if (!ShouldPropertyDisplayReadOnly(property) && ShouldMethodDisplayReadOnly(method, property)) { AddReadOnlyIfRequired(); } AddKeyword(keyword); AddPunctuation(SyntaxKind.SemicolonToken); } } private void AddExplicitInterfaceIfRequired<T>(ImmutableArray<T> implementedMembers) where T : ISymbol { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeExplicitInterface) && !implementedMembers.IsEmpty) { var implementedMember = implementedMembers[0]; Debug.Assert(implementedMember.ContainingType != null); INamedTypeSymbol containingType = implementedMember.ContainingType; if (containingType != null) { containingType.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.DotToken); } } } private void AddCustomModifiersIfRequired(ImmutableArray<CustomModifier> customModifiers, bool leadingSpace = false, bool trailingSpace = true) { if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers) && !customModifiers.IsEmpty) { bool first = true; foreach (CustomModifier customModifier in customModifiers) { if (!first || leadingSpace) { AddSpace(); } first = false; this.builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, null, customModifier.IsOptional ? IL_KEYWORD_MODOPT : IL_KEYWORD_MODREQ)); AddPunctuation(SyntaxKind.OpenParenToken); customModifier.Modifier.Accept(this.NotFirstVisitor); AddPunctuation(SyntaxKind.CloseParenToken); } if (trailingSpace) { AddSpace(); } } } private void AddRefIfRequired() { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddRef(); } } private void AddRef() { AddKeyword(SyntaxKind.RefKeyword); AddSpace(); } private void AddRefReadonlyIfRequired() { if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddRefReadonly(); } } private void AddRefReadonly() { AddKeyword(SyntaxKind.RefKeyword); AddSpace(); AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } private void AddReadOnlyIfRequired() { // 'readonly' in this context is effectively a 'ref' modifier // because it affects whether the 'this' parameter is 'ref' or 'in'. if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef)) { AddKeyword(SyntaxKind.ReadOnlyKeyword); AddSpace(); } } private void AddParameterRefKindIfRequired(RefKind refKind) { if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut)) { AddParameterRefKind(refKind); } } private void AddParameterRefKind(RefKind refKind) { switch (refKind) { case RefKind.Out: AddKeyword(SyntaxKind.OutKeyword); AddSpace(); break; case RefKind.Ref: AddKeyword(SyntaxKind.RefKeyword); AddSpace(); break; case RefKind.In: AddKeyword(SyntaxKind.InKeyword); AddSpace(); break; } } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.cs
// Licensed to the .NET Foundation under one or more 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.IO.MemoryMappedFiles; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryStorageServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? (ITemporaryStorageService)new TemporaryStorageService(textFactory) : TrivialTemporaryStorageService.Instance; } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { /// <summary> /// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other /// storage units. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long SingleFileThreshold = 128 * 1024; /// <summary> /// The size in bytes of a memory mapped file created to store multiple temporary objects. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long MultiFileBlockSize = SingleFileThreshold * 32; private readonly ITextFactoryService _textFactory; /// <summary> /// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks /// of each field). /// </summary> /// <remarks> /// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is /// available in source control history. The use of exclusive locks was not causing any measurable /// performance overhead even on 28-thread machines at the time this was written.</para> /// </remarks> private readonly object _gate = new(); /// <summary> /// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer /// allocation until space is no longer available in it. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference; /// <summary>The name of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private string? _name; /// <summary>The total size of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _fileSize; /// <summary> /// The offset into the current memory mapped file where the next storage unit can be held. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _offset; public TemporaryStorageService(ITextFactoryService textFactory) => _textFactory = textFactory; public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) => new TemporaryTextStorage(this); public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken) => new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding); public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) => new TemporaryStreamStorage(this); public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken) => new TemporaryStreamStorage(this, storageName, offset, size); /// <summary> /// Allocate shared storage of a specified size. /// </summary> /// <remarks> /// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual /// storage units. Larger requests are allocated in their own memory mapped files.</para> /// </remarks> /// <param name="size">The size of the shared storage block to allocate.</param> /// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns> private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable<MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return new MemoryMappedInfo(reference, _name, offset: 0, size: size); } else { // Reserve additional space in the existing storage location Contract.ThrowIfNull(_name); _offset += size; return new MemoryMappedInfo(reference, _name, _offset - size, size); } } } public static string CreateUniqueName(long size) => "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N"); private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName { private readonly TemporaryStorageService _service; private SourceHashAlgorithm _checksumAlgorithm; private Encoding? _encoding; private ImmutableArray<byte> _checksum; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) => _service = service; public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding) { _service = service; _checksumAlgorithm = checksumAlgorithm; _encoding = encoding; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: cleanup https://github.com/dotnet/roslyn/issues/43037 // Offet, Size not accessed if Name is null public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm; public Encoding? Encoding => _encoding; public ImmutableArray<byte> GetChecksum() { if (_checksum.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum()); } return _checksum; } public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; _encoding = null; } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using var stream = _memoryMappedInfo.CreateReadableStream(); using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length); // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _checksumAlgorithm = text.ChecksumAlgorithm; _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service.CreateTemporaryStorage(size); // Write the source text out as Unicode. We expect that to be cheap. using var stream = _memoryMappedInfo.CreateWritableStream(); using var writer = new StreamWriter(stream, Encoding.Unicode); text.Write(writer, cancellationToken); } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength) { var src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) => _service = service; public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size) { _service = service; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: clean up https://github.com/dotnet/roslyn/issues/43037 // Offset, Size is only used when Name is not null. public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default) => WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service.CreateTemporaryStorage(size); using var viewStream = _memoryMappedInfo.CreateWritableStream(); var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { RoslynDebug.Assert(src != null); RoslynDebug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
// Licensed to the .NET Foundation under one or more 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.IO.MemoryMappedFiles; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryStorageServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? (ITemporaryStorageService)new TemporaryStorageService(textFactory) : TrivialTemporaryStorageService.Instance; } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { /// <summary> /// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other /// storage units. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long SingleFileThreshold = 128 * 1024; /// <summary> /// The size in bytes of a memory mapped file created to store multiple temporary objects. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long MultiFileBlockSize = SingleFileThreshold * 32; private readonly ITextFactoryService _textFactory; /// <summary> /// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks /// of each field). /// </summary> /// <remarks> /// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is /// available in source control history. The use of exclusive locks was not causing any measurable /// performance overhead even on 28-thread machines at the time this was written.</para> /// </remarks> private readonly object _gate = new(); /// <summary> /// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer /// allocation until space is no longer available in it. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference; /// <summary>The name of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private string? _name; /// <summary>The total size of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _fileSize; /// <summary> /// The offset into the current memory mapped file where the next storage unit can be held. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _offset; public TemporaryStorageService(ITextFactoryService textFactory) => _textFactory = textFactory; public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) => new TemporaryTextStorage(this); public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken) => new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding); public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) => new TemporaryStreamStorage(this); public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken) => new TemporaryStreamStorage(this, storageName, offset, size); /// <summary> /// Allocate shared storage of a specified size. /// </summary> /// <remarks> /// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual /// storage units. Larger requests are allocated in their own memory mapped files.</para> /// </remarks> /// <param name="size">The size of the shared storage block to allocate.</param> /// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns> private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable<MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return new MemoryMappedInfo(reference, _name, offset: 0, size: size); } else { // Reserve additional space in the existing storage location Contract.ThrowIfNull(_name); _offset += size; return new MemoryMappedInfo(reference, _name, _offset - size, size); } } } public static string CreateUniqueName(long size) => "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N"); private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName { private readonly TemporaryStorageService _service; private SourceHashAlgorithm _checksumAlgorithm; private Encoding? _encoding; private ImmutableArray<byte> _checksum; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) => _service = service; public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding) { _service = service; _checksumAlgorithm = checksumAlgorithm; _encoding = encoding; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: cleanup https://github.com/dotnet/roslyn/issues/43037 // Offet, Size not accessed if Name is null public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm; public Encoding? Encoding => _encoding; public ImmutableArray<byte> GetChecksum() { if (_checksum.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum()); } return _checksum; } public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; _encoding = null; } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using var stream = _memoryMappedInfo.CreateReadableStream(); using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length); // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _checksumAlgorithm = text.ChecksumAlgorithm; _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service.CreateTemporaryStorage(size); // Write the source text out as Unicode. We expect that to be cheap. using var stream = _memoryMappedInfo.CreateWritableStream(); using var writer = new StreamWriter(stream, Encoding.Unicode); text.Write(writer, cancellationToken); } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength) { var src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) => _service = service; public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size) { _service = service; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: clean up https://github.com/dotnet/roslyn/issues/43037 // Offset, Size is only used when Name is not null. public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default) => WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service.CreateTemporaryStorage(size); using var viewStream = _memoryMappedInfo.CreateWritableStream(); var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { RoslynDebug.Assert(src != null); RoslynDebug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(GenericNamePartiallyWrittenSignatureHelpProvider); [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericUnterminated() { var markup = @" class G<T> { }; class C { void Goo() { G<G<int>$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterUnterminated() { var markup = @" class G<T> { }; class C { void Goo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericAsyncMethod() { var markup = @" using System.Threading.Tasks; class Program { void Main(string[] args) { Goo<$$ } Task<int> Goo<T>() { return Goo<T>(); } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<int> Program.Goo<T>()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableAlways() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableNever() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableMixed() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Goo<T>(T x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Goo<T, U>(T x, U y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task GenericExtensionMethod() { var markup = @" interface IGoo { void Bar<T>(); } static class GooExtensions { public static void Bar<T1, T2>(this IGoo goo) { } } class Program { static void Main() { IGoo f = null; f.[|Bar<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void IGoo.Bar<T>()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar<T1, T2>()", currentParameterIndex: 0), }; // Extension methods are supported in Interactive/Script (yet). await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterUnterminated() { var markup = @" class C { /// <summary> /// Method Goo /// </summary> /// <typeparam name=""T"">Method type parameter</typeparam> void Goo<T>() { } void Bar() { [|Goo<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()", "Method Goo", "Method type parameter", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerBracket() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<int,$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo<$$"; await TestAsync(markup); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(GenericNamePartiallyWrittenSignatureHelpProvider); [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericUnterminated() { var markup = @" class G<T> { }; class C { void Goo() { G<G<int>$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterUnterminated() { var markup = @" class G<T> { }; class C { void Goo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericAsyncMethod() { var markup = @" using System.Threading.Tasks; class Program { void Main(string[] args) { Goo<$$ } Task<int> Goo<T>() { return Goo<T>(); } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<int> Program.Goo<T>()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableAlways() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableNever() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public void Goo<T>(T x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericMethod_BrowsableMixed() { var markup = @" class Program { void M() { new C().Goo<$$ } } "; var referencedCode = @" public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public void Goo<T>(T x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public void Goo<T, U>(T x, U y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task GenericExtensionMethod() { var markup = @" interface IGoo { void Bar<T>(); } static class GooExtensions { public static void Bar<T1, T2>(this IGoo goo) { } } class Program { static void Main() { IGoo f = null; f.[|Bar<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void IGoo.Bar<T>()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar<T1, T2>()", currentParameterIndex: 0), }; // Extension methods are supported in Interactive/Script (yet). await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterUnterminated() { var markup = @" class C { /// <summary> /// Method Goo /// </summary> /// <typeparam name=""T"">Method type parameter</typeparam> void Goo<T>() { } void Bar() { [|Goo<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()", "Method Goo", "Method type parameter", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerBracket() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<int,$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo<$$"; await TestAsync(markup); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Features/LanguageServer/ProtocolUnitTests/DocumentChanges/DocumentChangesTests.LinkedDocuments.cs
// Licensed to the .NET Foundation under one or more 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.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges { public partial class DocumentChangesTests { protected override TestComposition Composition => base.Composition .AddParts(typeof(GetLspSolutionHandlerProvider)); [Fact] public async Task LinkedDocuments_AllTracked() { var documentText = "class C { }"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{documentText}{{|caret:|}}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var caretLocation = locations["caret"].Single(); await DidOpen(testLspServer, caretLocation.Uri); var trackedDocuments = testLspServer.GetQueueAccessor().GetTrackedTexts(); Assert.Equal(1, trackedDocuments.Count); var solution = await GetLSPSolution(testLspServer, caretLocation.Uri); foreach (var document in solution.Projects.First().Documents) { Assert.Equal(documentText, document.GetTextSynchronously(CancellationToken.None).ToString()); } await DidClose(testLspServer, caretLocation.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } [Fact] public async Task LinkedDocuments_AllTextChanged() { var initialText = @"class A { void M() { {|caret:|} } }"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{initialText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var caretLocation = locations["caret"].Single(); var updatedText = @"class A { void M() { // hi there } }"; await DidOpen(testLspServer, caretLocation.Uri); Assert.Equal(1, testLspServer.GetQueueAccessor().GetTrackedTexts().Count); await DidChange(testLspServer, caretLocation.Uri, (4, 8, "// hi there")); var solution = await GetLSPSolution(testLspServer, caretLocation.Uri); foreach (var document in solution.Projects.First().Documents) { Assert.Equal(updatedText, document.GetTextSynchronously(CancellationToken.None).ToString()); } await DidClose(testLspServer, caretLocation.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } private static Task<Solution> GetLSPSolution(TestLspServer testLspServer, Uri uri) { return testLspServer.ExecuteRequestAsync<Uri, Solution>(nameof(GetLSPSolutionHandler), uri, new ClientCapabilities(), null, CancellationToken.None); } [Shared, ExportRoslynLanguagesLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(GetLSPSolutionHandler.MethodName)] private class GetLspSolutionHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GetLspSolutionHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() => ImmutableArray.Create<IRequestHandler>(new GetLSPSolutionHandler()); } private class GetLSPSolutionHandler : IRequestHandler<Uri, Solution> { public const string MethodName = nameof(GetLSPSolutionHandler); public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier? GetTextDocumentIdentifier(Uri request) => new TextDocumentIdentifier { Uri = request }; public Task<Solution> HandleRequestAsync(Uri request, RequestContext context, CancellationToken cancellationToken) => Task.FromResult(context.Solution!); } } }
// Licensed to the .NET Foundation under one or more 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.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.DocumentChanges { public partial class DocumentChangesTests { protected override TestComposition Composition => base.Composition .AddParts(typeof(GetLspSolutionHandlerProvider)); [Fact] public async Task LinkedDocuments_AllTracked() { var documentText = "class C { }"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{documentText}{{|caret:|}}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var caretLocation = locations["caret"].Single(); await DidOpen(testLspServer, caretLocation.Uri); var trackedDocuments = testLspServer.GetQueueAccessor().GetTrackedTexts(); Assert.Equal(1, trackedDocuments.Count); var solution = await GetLSPSolution(testLspServer, caretLocation.Uri); foreach (var document in solution.Projects.First().Documents) { Assert.Equal(documentText, document.GetTextSynchronously(CancellationToken.None).ToString()); } await DidClose(testLspServer, caretLocation.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } [Fact] public async Task LinkedDocuments_AllTextChanged() { var initialText = @"class A { void M() { {|caret:|} } }"; var workspaceXml = @$"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{initialText}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var caretLocation = locations["caret"].Single(); var updatedText = @"class A { void M() { // hi there } }"; await DidOpen(testLspServer, caretLocation.Uri); Assert.Equal(1, testLspServer.GetQueueAccessor().GetTrackedTexts().Count); await DidChange(testLspServer, caretLocation.Uri, (4, 8, "// hi there")); var solution = await GetLSPSolution(testLspServer, caretLocation.Uri); foreach (var document in solution.Projects.First().Documents) { Assert.Equal(updatedText, document.GetTextSynchronously(CancellationToken.None).ToString()); } await DidClose(testLspServer, caretLocation.Uri); Assert.Empty(testLspServer.GetQueueAccessor().GetTrackedTexts()); } private static Task<Solution> GetLSPSolution(TestLspServer testLspServer, Uri uri) { return testLspServer.ExecuteRequestAsync<Uri, Solution>(nameof(GetLSPSolutionHandler), uri, new ClientCapabilities(), null, CancellationToken.None); } [Shared, ExportRoslynLanguagesLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(GetLSPSolutionHandler.MethodName)] private class GetLspSolutionHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GetLspSolutionHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() => ImmutableArray.Create<IRequestHandler>(new GetLSPSolutionHandler()); } private class GetLSPSolutionHandler : IRequestHandler<Uri, Solution> { public const string MethodName = nameof(GetLSPSolutionHandler); public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier? GetTextDocumentIdentifier(Uri request) => new TextDocumentIdentifier { Uri = request }; public Task<Solution> HandleRequestAsync(Uri request, RequestContext context, CancellationToken cancellationToken) => Task.FromResult(context.Solution!); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Features/Core/Portable/GoToDefinition/IFindDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.GoToDefinition { internal interface IFindDefinitionService : ILanguageService { /// <summary> /// Finds the definitions for the symbol at the specific position in the document. /// </summary> Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.GoToDefinition { internal interface IFindDefinitionService : ILanguageService { /// <summary> /// Finds the definitions for the symbol at the specific position in the document. /// </summary> Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/Test/MetadataAsSource/DocCommentFormatterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) => TestFormat(docCommentXmlFragment, expected, expected); private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns_colon} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Value() { var comment = @"<value>A string value</value>"; var expected = $@"{FeaturesResources.Value_colon} A string value"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary_colon} This is the summary. {FeaturesResources.Parameters_colon} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.Type_parameters_colon} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <value>This has no value.</value> <exception cref=""System.GooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary of something. {FeaturesResources.Parameters_colon} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.Type_parameters_colon} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns_colon} This returns nothing. {FeaturesResources.Value_colon} This has no value. {FeaturesResources.Exceptions_colon} System.GooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks_colon} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private readonly CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private readonly VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) => TestFormat(docCommentXmlFragment, expected, expected); private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary_colon} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions_colon} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns_colon} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Value() { var comment = @"<value>A string value</value>"; var expected = $@"{FeaturesResources.Value_colon} A string value"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary_colon} This is the summary. {FeaturesResources.Parameters_colon} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.Type_parameters_colon} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <value>This has no value.</value> <exception cref=""System.GooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary_colon} This is a summary of something. {FeaturesResources.Parameters_colon} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.Type_parameters_colon} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns_colon} This returns nothing. {FeaturesResources.Value_colon} This has no value. {FeaturesResources.Exceptions_colon} System.GooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks_colon} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers.GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateEqualsAndGetHashCodeFromMembers { [UseExportProvider] public class GenerateEqualsAndGetHashCodeFromMembersTests { private class TestWithDialog : VerifyCS.Test { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.AddParts(typeof(TestPickMembersService)); public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; protected override Workspace CreateWorkspaceImpl() { // If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for. var workspace = new AdhocWorkspace(s_composition.GetHostServices()); var service = (TestPickMembersService)workspace.Services.GetService<IPickMembersService>(); service.MemberNames = MemberNames; service.OptionsCallback = OptionsCallback; return workspace; } } private static OptionsCollection PreferImplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion }, }; private static OptionsCollection PreferExplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, false, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, false, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Suggestion }, }; internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField() { var code = @"using System.Collections.Generic; class Program { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { var program = obj as Program; return program != null && a == program.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField_PreferExplicitType() { var code = @"using System.Collections.Generic; class Program { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { Program program = obj as Program; return program != null && a == program.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestReferenceIEquatable() { var code = @" using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { [|S a;|] }"; var fixedCode = @" using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { S a; public override bool Equals(object obj) { var program = obj as Program; return program != null && EqualityComparer<S>.Default.Equals(a, program.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestNullableReferenceIEquatable() { var code = @"#nullable enable using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { [|S? a;|] }"; var fixedCode = @"#nullable enable using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { S? a; public override bool Equals(object? obj) { return obj is Program program && EqualityComparer<S?>.Default.Equals(a, program.a); } public override int GetHashCode() { return -1757793268 + EqualityComparer<S?>.Default.GetHashCode(a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestValueIEquatable() { var code = @" using System; using System.Collections.Generic; struct S : {|CS0535:IEquatable<S>|} { } class Program { [|S a;|] }"; var fixedCode = @" using System; using System.Collections.Generic; struct S : {|CS0535:IEquatable<S>|} { } class Program { S a; public override bool Equals(object obj) { var program = obj as Program; return program != null && a.Equals(program.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsLongName() { var code = @"using System.Collections.Generic; class ReallyLongName { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongName { int a; public override bool Equals(object obj) { var name = obj as ReallyLongName; return name != null && a == name.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsKeywordName() { var code = @"using System.Collections.Generic; class ReallyLongLong { [|long a;|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongLong { long a; public override bool Equals(object obj) { var @long = obj as ReallyLongLong; return @long != null && a == @long.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsProperty() { var code = @"using System.Collections.Generic; class ReallyLongName { [|int a; string B { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongName { int a; string B { get; } public override bool Equals(object obj) { var name = obj as ReallyLongName; return name != null && a == name.a && B == name.B; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseTypeWithNoEquals() { var code = @"class Base { } class Program : Base { [|int i;|] }"; var fixedCode = @"class Base { } class Program : Base { int i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseWithOverriddenEquals() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsOverriddenDeepBase() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Middle : Base { } class Program : Middle { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Middle : Base { } class Program : Middle { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStruct() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructCSharpLatest() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyImplementsIEquatable() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && i == name.i && S == name.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyHasOperators() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { [|int i; string S { get; }|] public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }", @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && i == name.i && S == name.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsGenericType() { var code = @" using System.Collections.Generic; class Program<T> { [|int i;|] } "; var expected = @" using System.Collections.Generic; class Program<T> { int i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && i == program.i; } } "; await new VerifyCS.Test { TestCode = code, FixedCode = expected, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsNullableContext() { await VerifyCS.VerifyRefactoringAsync( @"#nullable enable class Program { [|int a;|] }", @"#nullable enable class Program { int a; public override bool Equals(object? obj) { return obj is Program program && a == program.a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField1() { var code = @"using System.Collections.Generic; class Program { [|int i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i; } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField2() { var code = @"using System.Collections.Generic; class Program { [|int j;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null && j == program.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeWithBaseHashCode1() { var code = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { [|int j;|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null && j == program.j; } public override int GetHashCode() { var hashCode = 339610899; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + j.GetHashCode(); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeWithBaseHashCode2() { var code = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; [||] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null; } public override int GetHashCode() { return 624022166 + base.GetHashCode(); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, MemberNames = ImmutableArray<string>.Empty, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField_CodeStyle1() { var code = @"using System.Collections.Generic; class Program { [|int i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; public override bool Equals(object obj) { Program program = obj as Program; return program != null && i == program.i; } public override int GetHashCode() => 165851236 + i.GetHashCode(); }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeTypeParameter() { var code = @"using System.Collections.Generic; class Program<T> { [|T i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program<T> { T i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && EqualityComparer<T>.Default.Equals(i, program.i); } public override int GetHashCode() { return 165851236 + EqualityComparer<T>.Default.GetHashCode(i); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeGenericType() { var code = @"using System.Collections.Generic; class Program<T> { [|Program<T> i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program<T> { Program<T> i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && EqualityComparer<Program<T>>.Default.Equals(i, program.i); } public override int GetHashCode() { return 165851236 + EqualityComparer<Program<T>>.Default.GetHashCode(i); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeMultipleMembers() { var code = @"using System.Collections.Generic; class Program { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i && S == program.S; } public override int GetHashCode() { var hashCode = -538000506; hashCode = hashCode * -1521134295 + i.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText1() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_object, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_object, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText2() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } public override int GetHashCode() { int hashCode = -666523601; hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText3() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } public override int GetHashCode() { int hashCode = -666523601; hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_Disabled() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int, string)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuples_Equals() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int, string)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_Equals() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int x, string y)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int x, string y)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_HashCode() { var code = @"using System.Collections.Generic; class Program { [|{|CS8059:(int, string)|} i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { {|CS8059:(int, string)|} i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i.Equals(program.i); } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_HashCode() { var code = @"using System.Collections.Generic; class Program { [|{|CS8059:(int x, string y)|} i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { {|CS8059:(int x, string y)|} i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i.Equals(program.i); } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } struct Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } struct Bar { public override int GetHashCode() => 0; }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { public override int GetHashCode() => 0; }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar? bar;|] } struct Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar? bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar?>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructTypeParameter_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { [|TBar bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { TBar bar; public override bool Equals(object obj) { var foo = obj as Foo<TBar>; return foo != null && EqualityComparer<TBar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { [|TBar? bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { TBar? bar; public override bool Equals(object obj) { var foo = obj as Foo<TBar>; return foo != null && EqualityComparer<TBar?>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Enum_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } enum Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && bar == foo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } enum Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task PrimitiveValueType_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|ulong bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo { ulong bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && bar == foo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog1() { var code = @"using System.Collections.Generic; class Program { int a; string b; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; public override bool Equals(object obj) { var program = obj as Program; return program != null && a == program.a && b == program.b; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray.Create("a", "b"), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog2() { var code = @"using System.Collections.Generic; class Program { int a; string b; bool c; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; bool c; public override bool Equals(object obj) { var program = obj as Program; return program != null && c == program.c && b == program.b; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray.Create("c", "b"), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog3() { var code = @"using System.Collections.Generic; class Program { int a; string b; bool c; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; bool c; public override bool Equals(object obj) { var program = obj as Program; return program != null; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray<string>.Empty, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoBackingField() { var code = @" class Program { public int F { get; set; } [||] }"; var fixedCode = @" class Program { public int F { get; set; } public override bool Equals(object obj) { var program = obj as Program; return program != null && F == program.F; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoIndexer() { var code = @" class Program { public int P => 0; public int this[int index] => 0; [||] }"; var fixedCode = @" class Program { public int P => 0; public int this[int index] => 0; public override bool Equals(object obj) { return obj is Program program && P == program.P; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoSetterOnlyProperty() { var code = @" class Program { public int P => 0; public int S { set { } } [||] }"; var fixedCode = @" class Program { public int P => 0; public int S { set { } } public override bool Equals(object obj) { return obj is Program program && P == program.P; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogInheritedMembers() { var code = @" class Base { public int C { get; set; } } class Middle : Base { public int B { get; set; } } class Derived : Middle { public int A { get; set; } [||] }"; var fixedCode = @" class Base { public int C { get; set; } } class Middle : Base { public int B { get; set; } } class Derived : Middle { public int A { get; set; } public override bool Equals(object obj) { return obj is Derived derived && C == derived.C && B == derived.B && A == derived.A; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators1() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } public static bool operator ==(Program left, Program right) { return EqualityComparer<Program>.Default.Equals(left, right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators2() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { Program program = obj as Program; return program != null && s == program.s; } public static bool operator ==(Program left, Program right) => EqualityComparer<Program>.Default.Equals(left, right); public static bool operator !=(Program left, Program right) => !(left == right); }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators3() { var code = @" using System.Collections.Generic; class Program { public string s; [||] public static bool operator {|CS0216:==|}(Program left, Program right) => true; }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } public static bool operator {|CS0216:==|}(Program left, Program right) => true; }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators4() { var code = @" using System.Collections.Generic; struct Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; struct Program { public string s; public override bool Equals(object obj) { if (!(obj is Program)) { return false; } var program = (Program)obj; return s == program.s; } public static bool operator ==(Program left, Program right) { return left.Equals(right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateLiftedOperators() { var code = @" using System; using System.Collections.Generic; class Foo { [|public bool? BooleanValue { get; } public decimal? DecimalValue { get; } public Bar? EnumValue { get; } public DateTime? DateTimeValue { get; }|] } enum Bar { }"; var fixedCode = @" using System; using System.Collections.Generic; class Foo { public bool? BooleanValue { get; } public decimal? DecimalValue { get; } public Bar? EnumValue { get; } public DateTime? DateTimeValue { get; } public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && BooleanValue == foo.BooleanValue && DecimalValue == foo.DecimalValue && EnumValue == foo.EnumValue && DateTimeValue == foo.DateTimeValue; } } enum Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed() { var code = @" using System; using System.Collections.Generic; class Foo { [|public Bar Value { get; } public Bar? NullableValue { get; }|] } struct Bar : IEquatable<Bar> { private readonly int value; public override bool Equals(object obj) => false; public bool Equals(Bar other) => value == other.value; public override int GetHashCode() => -1584136870 + value.GetHashCode(); public static bool operator ==(Bar left, Bar right) => left.Equals(right); public static bool operator !=(Bar left, Bar right) => !(left == right); }"; var fixedCode = @" using System; using System.Collections.Generic; class Foo { public Bar Value { get; } public Bar? NullableValue { get; } public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && Value.Equals(foo.Value) && EqualityComparer<Bar?>.Default.Equals(NullableValue, foo.NullableValue); } } struct Bar : IEquatable<Bar> { private readonly int value; public override bool Equals(object obj) => false; public bool Equals(Bar other) => value == other.value; public override int GetHashCode() => -1584136870 + value.GetHashCode(); public static bool operator ==(Bar left, Bar right) => left.Equals(right); public static bool operator !=(Bar left, Bar right) => !(left == right); }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStruct() { var code = @" using System.Collections.Generic; struct Program { public string s; [||] }"; var fixedCode = @" using System; using System.Collections.Generic; struct Program : IEquatable<Program> { public string s; public override bool Equals(object obj) { return obj is Program && Equals((Program)obj); } public bool Equals(Program other) { return s == other.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")] public async Task TestOverrideEqualsOnRefStructReturnsFalse() { var code = @" ref struct Program { public string s; [||] }"; var fixedCode = @" ref struct Program { public string s; public override bool Equals(object obj) { return false; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")] public async Task TestImplementIEquatableOnRefStructSkipsIEquatable() { var code = @" ref struct Program { public string s; [||] }"; var fixedCode = @" ref struct Program { public string s; public override bool Equals(object obj) { return false; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, // We are forcefully enabling the ImplementIEquatable option, as that is our way // to test that the option does nothing. The VS mode will ensure if the option // is not available it will not be shown. OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata() { var code = @"#nullable enable struct Foo { public int Bar { get; } [||] }"; var fixedCode = @"#nullable enable using System; struct Foo : IEquatable<Foo> { public int Bar { get; } public override bool Equals(object? obj) { return obj is Foo foo && Equals(foo); } public bool Equals(Foo other) { return Bar == other.Bar; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata() { var code = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; struct Foo { public bool Bar { get; } [||] } "; var fixedCode = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; struct Foo : IEquatable<Foo> { public bool Bar { get; } public override bool Equals(object? obj) { return obj is Foo foo && Equals(foo); } public bool Equals(Foo other) { return Bar == other.Bar; } } "; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClass() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System; using System.Collections.Generic; class Program : IEquatable<Program> { public string s; public override bool Equals(object obj) { return Equals(obj as Program); } public bool Equals(Program other) { return other != null && s == other.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata() { var code = @"#nullable enable class Foo { public int Bar { get; } [||] }"; var fixedCode = @"#nullable enable using System; class Foo : IEquatable<Foo?> { public int Bar { get; } public override bool Equals(object? obj) { return Equals(obj as Foo); } public bool Equals(Foo? other) { return other != null && Bar == other.Bar; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata() { var code = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; class Foo { public bool Bar { get; } [||] } "; var fixedCode = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; class Foo : IEquatable<Foo?> { public bool Bar { get; } public override bool Equals(object? obj) { return Equals(obj as Foo); } public bool Equals(Foo? other) { return other != null && Bar == other.Bar; } } "; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt() { var code = @" using System.Collections.Generic; class Program : {|CS0535:System.IEquatable<Program>|} { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program : {|CS0535:System.IEquatable<Program>|} { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestMissingReferences1() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp6, CodeActionIndex = 1, TestState = { Sources = { @"public class Class1 { [|int i;|] public void F() { } }", }, ExpectedDiagnostics = { // /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"), // /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"), // /0/Test0.cs(5,12): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 12, 5, 16).WithArguments("System.Void"), }, }, FixedState = { Sources = { @"public class Class1 { int i; public override System.Boolean Equals(System.Object obj) { Class1 @class = obj as Class1; return @class != null && i == @class.i; } public void F() { } public override System.Int32 GetHashCode() { return 165851236 + EqualityComparer<System.Int32>.Default.GetHashCode(i); } }", }, ExpectedDiagnostics = { // /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"), // /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"), // /0/Test0.cs(5,21): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 21, 5, 27).WithArguments("System.Object"), // /0/Test0.cs(5,28): error CS1069: The type name 'Boolean' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(5, 28, 5, 35).WithArguments("Boolean", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 43, 5, 49).WithArguments("System.Object"), // /0/Test0.cs(5,50): error CS1069: The type name 'Object' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(5, 50, 5, 56).WithArguments("Object", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(7,9): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(7, 9, 7, 15).WithArguments("System.Object"), // /0/Test0.cs(7,32): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(7, 32, 7, 38).WithArguments("System.Object"), // /0/Test0.cs(8,16): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(8, 16, 8, 30).WithArguments("System.Object"), // /0/Test0.cs(9,16): error CS0518: Predefined type 'System.Boolean' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(9, 16, 9, 29).WithArguments("System.Boolean"), // /0/Test0.cs(12,12): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(12, 12, 12, 16).WithArguments("System.Void"), // /0/Test0.cs(16,21): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(16, 21, 16, 27).WithArguments("System.Object"), // /0/Test0.cs(16,28): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(16, 28, 16, 33).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(16,34): error CS0115: 'Class1.GetHashCode()': no suitable method found to override DiagnosticResult.CompilerError("CS0115").WithSpan(16, 34, 16, 45).WithArguments("Class1.GetHashCode()"), // /0/Test0.cs(18,16): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 16, 18, 25).WithArguments("System.Int32"), // /0/Test0.cs(18,28): error CS0103: The name 'EqualityComparer' does not exist in the current context DiagnosticResult.CompilerError("CS0103").WithSpan(18, 28, 18, 58).WithArguments("EqualityComparer"), // /0/Test0.cs(18,28): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 28, 18, 58).WithArguments("System.Object"), // /0/Test0.cs(18,45): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 45, 18, 51).WithArguments("System.Object"), // /0/Test0.cs(18,52): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(18, 52, 18, 57).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), }, }, ReferenceAssemblies = ReferenceAssemblies.Default.WithAssemblies(ImmutableArray<string>.Empty), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeInCheckedContext() { var code = @"using System.Collections.Generic; class Program { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; string S { get; } public override bool Equals(object obj) { Program program = obj as Program; return program != null && i == program.i && S == program.S; } public override int GetHashCode() { unchecked { int hashCode = -538000506; hashCode = hashCode * -1521134295 + i.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S); return hashCode; } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetRequiredProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOverflowChecks(true)); }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeStruct() { var code = @"using System.Collections.Generic; struct S { [|int j;|] }"; var fixedCode = @"using System; using System.Collections.Generic; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeOneMember() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { } } struct S { [|int j;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { } } struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return HashCode.Combine(j); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(21,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(21, 25, 21, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPublicSystemHashCodeOtherProject() { var publicHashCode = @"using System.Collections.Generic; namespace System { public struct HashCode { } }"; var code = @"struct S { [|int j;|] }"; var fixedCode = @"using System; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return HashCode.Combine(j); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestState = { AdditionalProjects = { ["P1"] = { Sources = { ("HashCode.cs", publicHashCode) }, }, }, Sources = { code }, AdditionalProjectReferences = { "P1" }, }, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(19,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(19, 25, 19, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestInternalSystemHashCode() { var internalHashCode = @"using System.Collections.Generic; namespace System { internal struct HashCode { } }"; var code = @"struct S { [|int j;|] }"; var fixedCode = @"using System; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestState = { AdditionalProjects = { ["P1"] = { Sources = { ("HashCode.cs", internalHashCode) }, }, }, Sources = { code }, AdditionalProjectReferences = { "P1" }, }, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeEightMembers() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { } } struct S { [|int j, k, l, m, n, o, p, q;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q; } public override int GetHashCode() { return HashCode.Combine(j, k, l, m, n, o, p, q); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(28,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(28, 25, 28, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeNineMembers() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S { [|int j, k, l, m, n, o, p, q, r;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q, r; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q && r == other.r; } public override int GetHashCode() { var hash = new HashCode(); hash.Add(j); hash.Add(k); hash.Add(l); hash.Add(m); hash.Add(n); hash.Add(o); hash.Add(p); hash.Add(q); hash.Add(r); return hash.ToHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeNineMembers_Explicit() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S { [|int j, k, l, m, n, o, p, q, r;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q, r; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q && r == other.r; } public override int GetHashCode() { HashCode hash = new HashCode(); hash.Add(j); hash.Add(k); hash.Add(l); hash.Add(m); hash.Add(n); hash.Add(o); hash.Add(p); hash.Add(q); hash.Add(r); return hash.ToHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField_Patterns() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; class Program { [|int a;|] }", @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { return obj is Program program && a == program.a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleFieldInStruct_Patterns() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct Program { [|int a;|] }", @"using System; using System.Collections.Generic; struct Program : IEquatable<Program> { int a; public override bool Equals(object obj) { return obj is Program program && Equals(program); } public bool Equals(Program other) { return a == other.a; } public static bool operator ==(Program left, Program right) { return left.Equals(right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseWithOverriddenEquals_Patterns() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { int i; string S { get; } public override bool Equals(object obj) { return obj is Program program && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, }.RunAsync(); } [WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialSelection() { var code = @"using System.Collections.Generic; class Program { int [|a|]; }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, }.RunAsync(); } [WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualityOperatorsNullableAnnotationWithReferenceType() { var code = @" #nullable enable using System; namespace N { public class C[||] { public int X; } }"; var fixedCode = @" #nullable enable using System; using System.Collections.Generic; namespace N { public class C { public int X; public override bool Equals(object? obj) { return obj is C c && X == c.X; } public static bool operator ==(C? left, C? right) { return EqualityComparer<C>.Default.Equals(left, right); } public static bool operator !=(C? left, C? right) { return !(left == right); } } }"; await new TestWithDialog { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(20,55): error CS8604: Possible null reference argument for parameter 'x' in 'bool EqualityComparer<C>.Equals(C x, C y)'. DiagnosticResult.CompilerError("CS8604").WithSpan(20, 55, 20, 59).WithArguments("x", "bool EqualityComparer<C>.Equals(C x, C y)"), // /0/Test0.cs(20,61): error CS8604: Possible null reference argument for parameter 'y' in 'bool EqualityComparer<C>.Equals(C x, C y)'. DiagnosticResult.CompilerError("CS8604").WithSpan(20, 61, 20, 66).WithArguments("y", "bool EqualityComparer<C>.Equals(C x, C y)"), }, }, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.Default, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualityOperatorsNullableAnnotationWithValueType() { var code = @" #nullable enable using System; namespace N { public struct C[||] { public int X; } }"; var fixedCode = @" #nullable enable using System; namespace N { public struct C { public int X; public override bool Equals(object? obj) { return obj is C c && X == c.X; } public static bool operator ==(C left, C right) { return left.Equals(right); } public static bool operator !=(C left, C right) { return !(left == right); } } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.Default, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes1() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { int bar; [||] }", @"partial class Goo { }", }, }, FixedState = { Sources = { @"partial class Goo { int bar; public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", @"partial class Goo { }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes2() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { int bar; }", @"partial class Goo { [||] }", }, }, FixedState = { Sources = { @"partial class Goo { int bar; }", @"partial class Goo { public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes3() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { [||] }", @"partial class Goo { int bar; }", }, }, FixedState = { Sources = { @"partial class Goo { public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", @"partial class Goo { int bar; }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes4() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { }", @"partial class Goo { int bar; [||] }", }, }, FixedState = { Sources = { @"partial class Goo { }", @"partial class Goo { int bar; public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestAbstractBase() { var code = @" #nullable enable namespace System { public struct HashCode { } } abstract class Base { public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); } class {|CS0534:{|CS0534:Derived|}|} : Base { [|public int P { get; }|] }"; var fixedCode = @" #nullable enable using System; namespace System { public struct HashCode { } } abstract class Base { public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); } class Derived : Base { public int P { get; } public override bool Equals(object? obj) { return obj is Derived derived && P == derived.P; } public override int GetHashCode() { return HashCode.Combine(P); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(23,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(26, 25, 26, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.Default, }.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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers.GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateEqualsAndGetHashCodeFromMembers { [UseExportProvider] public class GenerateEqualsAndGetHashCodeFromMembersTests { private class TestWithDialog : VerifyCS.Test { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.AddParts(typeof(TestPickMembersService)); public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; protected override Workspace CreateWorkspaceImpl() { // If we're a dialog test, then mixin our mock and initialize its values to the ones the test asked for. var workspace = new AdhocWorkspace(s_composition.GetHostServices()); var service = (TestPickMembersService)workspace.Services.GetService<IPickMembersService>(); service.MemberNames = MemberNames; service.OptionsCallback = OptionsCallback; return workspace; } } private static OptionsCollection PreferImplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion }, }; private static OptionsCollection PreferExplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, false, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, false, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Suggestion }, }; internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField() { var code = @"using System.Collections.Generic; class Program { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { var program = obj as Program; return program != null && a == program.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField_PreferExplicitType() { var code = @"using System.Collections.Generic; class Program { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { Program program = obj as Program; return program != null && a == program.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestReferenceIEquatable() { var code = @" using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { [|S a;|] }"; var fixedCode = @" using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { S a; public override bool Equals(object obj) { var program = obj as Program; return program != null && EqualityComparer<S>.Default.Equals(a, program.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestNullableReferenceIEquatable() { var code = @"#nullable enable using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { [|S? a;|] }"; var fixedCode = @"#nullable enable using System; using System.Collections.Generic; class S : {|CS0535:IEquatable<S>|} { } class Program { S? a; public override bool Equals(object? obj) { return obj is Program program && EqualityComparer<S?>.Default.Equals(a, program.a); } public override int GetHashCode() { return -1757793268 + EqualityComparer<S?>.Default.GetHashCode(a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestValueIEquatable() { var code = @" using System; using System.Collections.Generic; struct S : {|CS0535:IEquatable<S>|} { } class Program { [|S a;|] }"; var fixedCode = @" using System; using System.Collections.Generic; struct S : {|CS0535:IEquatable<S>|} { } class Program { S a; public override bool Equals(object obj) { var program = obj as Program; return program != null && a.Equals(program.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsLongName() { var code = @"using System.Collections.Generic; class ReallyLongName { [|int a;|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongName { int a; public override bool Equals(object obj) { var name = obj as ReallyLongName; return name != null && a == name.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsKeywordName() { var code = @"using System.Collections.Generic; class ReallyLongLong { [|long a;|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongLong { long a; public override bool Equals(object obj) { var @long = obj as ReallyLongLong; return @long != null && a == @long.a; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsProperty() { var code = @"using System.Collections.Generic; class ReallyLongName { [|int a; string B { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class ReallyLongName { int a; string B { get; } public override bool Equals(object obj) { var name = obj as ReallyLongName; return name != null && a == name.a && B == name.B; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseTypeWithNoEquals() { var code = @"class Base { } class Program : Base { [|int i;|] }"; var fixedCode = @"class Base { } class Program : Base { int i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseWithOverriddenEquals() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsOverriddenDeepBase() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Middle : Base { } class Program : Middle { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Middle : Base { } class Program : Middle { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStruct() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructCSharpLatest() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyImplementsIEquatable() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { [|int i; string S { get; }|] }", @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && i == name.i && S == name.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) { return left.Equals(right); } public static bool operator !=(ReallyLongName left, ReallyLongName right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyHasOperators() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName { [|int i; string S { get; }|] public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }", @"using System; using System.Collections.Generic; struct ReallyLongName : IEquatable<ReallyLongName> { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && Equals(name); } public bool Equals(ReallyLongName other) { return i == other.i && S == other.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStructAlreadyImplementsIEquatableAndHasOperators() { await VerifyCS.VerifyRefactoringAsync( @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { [|int i; string S { get; }|] public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }", @"using System; using System.Collections.Generic; struct ReallyLongName : {|CS0535:IEquatable<ReallyLongName>|} { int i; string S { get; } public override bool Equals(object obj) { return obj is ReallyLongName name && i == name.i && S == name.S; } public static bool operator ==(ReallyLongName left, ReallyLongName right) => false; public static bool operator !=(ReallyLongName left, ReallyLongName right) => false; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsGenericType() { var code = @" using System.Collections.Generic; class Program<T> { [|int i;|] } "; var expected = @" using System.Collections.Generic; class Program<T> { int i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && i == program.i; } } "; await new VerifyCS.Test { TestCode = code, FixedCode = expected, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsNullableContext() { await VerifyCS.VerifyRefactoringAsync( @"#nullable enable class Program { [|int a;|] }", @"#nullable enable class Program { int a; public override bool Equals(object? obj) { return obj is Program program && a == program.a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField1() { var code = @"using System.Collections.Generic; class Program { [|int i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i; } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField2() { var code = @"using System.Collections.Generic; class Program { [|int j;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null && j == program.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeWithBaseHashCode1() { var code = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { [|int j;|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null && j == program.j; } public override int GetHashCode() { var hashCode = 339610899; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + j.GetHashCode(); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeWithBaseHashCode2() { var code = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; [||] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override int GetHashCode() => 0; } class Program : Base { int j; public override bool Equals(object obj) { var program = obj as Program; return program != null; } public override int GetHashCode() { return 624022166 + base.GetHashCode(); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, MemberNames = ImmutableArray<string>.Empty, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField_CodeStyle1() { var code = @"using System.Collections.Generic; class Program { [|int i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; public override bool Equals(object obj) { Program program = obj as Program; return program != null && i == program.i; } public override int GetHashCode() => 165851236 + i.GetHashCode(); }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeTypeParameter() { var code = @"using System.Collections.Generic; class Program<T> { [|T i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program<T> { T i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && EqualityComparer<T>.Default.Equals(i, program.i); } public override int GetHashCode() { return 165851236 + EqualityComparer<T>.Default.GetHashCode(i); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeGenericType() { var code = @"using System.Collections.Generic; class Program<T> { [|Program<T> i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program<T> { Program<T> i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && EqualityComparer<Program<T>>.Default.Equals(i, program.i); } public override int GetHashCode() { return 165851236 + EqualityComparer<Program<T>>.Default.GetHashCode(i); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeMultipleMembers() { var code = @"using System.Collections.Generic; class Program { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; string S { get; } public override bool Equals(object obj) { var program = obj as Program; return program != null && i == program.i && S == program.S; } public override int GetHashCode() { var hashCode = -538000506; hashCode = hashCode * -1521134295 + i.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText1() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_object, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_object, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText2() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } public override int GetHashCode() { int hashCode = -666523601; hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText3() { var code = @"using System.Collections.Generic; class Program { [|bool b; HashSet<string> s;|] public Program(bool b) { this.b = b; } }"; var fixedCode = @"using System.Collections.Generic; class Program { bool b; HashSet<string> s; public Program(bool b) { this.b = b; } public override bool Equals(object obj) { return obj is Program program && b == program.b && EqualityComparer<HashSet<string>>.Default.Equals(s, program.s); } public override int GetHashCode() { int hashCode = -666523601; hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<HashSet<string>>.Default.GetHashCode(s); return hashCode; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, CodeActionEquivalenceKey = FeaturesResources.Generate_Equals_and_GetHashCode, CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Generate_Equals_and_GetHashCode, codeAction.Title), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_Disabled() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int, string)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuples_Equals() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int, string)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int, string)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_Equals() { var code = @"using System.Collections.Generic; class C { [|{|CS8059:(int x, string y)|} a;|] }"; var fixedCode = @"using System.Collections.Generic; class C { {|CS8059:(int x, string y)|} a; public override bool Equals(object obj) { var c = obj as C; return c != null && a.Equals(c.a); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_HashCode() { var code = @"using System.Collections.Generic; class Program { [|{|CS8059:(int, string)|} i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { {|CS8059:(int, string)|} i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i.Equals(program.i); } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_HashCode() { var code = @"using System.Collections.Generic; class Program { [|{|CS8059:(int x, string y)|} i;|] }"; var fixedCode = @"using System.Collections.Generic; class Program { {|CS8059:(int x, string y)|} i; public override bool Equals(object obj) { var program = obj as Program; return program != null && i.Equals(program.i); } public override int GetHashCode() { return 165851236 + i.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } struct Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructWithGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } struct Bar { public override int GetHashCode() => 0; }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { public override int GetHashCode() => 0; }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task NullableStructWithoutGetHashCodeOverride_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar? bar;|] } struct Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar? bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && EqualityComparer<Bar?>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } struct Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task StructTypeParameter_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { [|TBar bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { TBar bar; public override bool Equals(object obj) { var foo = obj as Foo<TBar>; return foo != null && EqualityComparer<TBar>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task NullableStructTypeParameter_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { [|TBar? bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo<TBar> where TBar : struct { TBar? bar; public override bool Equals(object obj) { var foo = obj as Foo<TBar>; return foo != null && EqualityComparer<TBar?>.Default.Equals(bar, foo.bar); } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Enum_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|Bar bar;|] } enum Bar { }"; var fixedCode = @"using System.Collections.Generic; class Foo { Bar bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && bar == foo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } } enum Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task PrimitiveValueType_ShouldCallGetHashCodeDirectly() { var code = @"using System.Collections.Generic; class Foo { [|ulong bar;|] }"; var fixedCode = @"using System.Collections.Generic; class Foo { ulong bar; public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && bar == foo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog1() { var code = @"using System.Collections.Generic; class Program { int a; string b; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; public override bool Equals(object obj) { var program = obj as Program; return program != null && a == program.a && b == program.b; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray.Create("a", "b"), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog2() { var code = @"using System.Collections.Generic; class Program { int a; string b; bool c; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; bool c; public override bool Equals(object obj) { var program = obj as Program; return program != null && c == program.c && b == program.b; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray.Create("c", "b"), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialog3() { var code = @"using System.Collections.Generic; class Program { int a; string b; bool c; [||] }"; var fixedCode = @"using System.Collections.Generic; class Program { int a; string b; bool c; public override bool Equals(object obj) { var program = obj as Program; return program != null; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = ImmutableArray<string>.Empty, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoBackingField() { var code = @" class Program { public int F { get; set; } [||] }"; var fixedCode = @" class Program { public int F { get; set; } public override bool Equals(object obj) { var program = obj as Program; return program != null && F == program.F; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(25690, "https://github.com/dotnet/roslyn/issues/25690")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoIndexer() { var code = @" class Program { public int P => 0; public int this[int index] => 0; [||] }"; var fixedCode = @" class Program { public int P => 0; public int this[int index] => 0; public override bool Equals(object obj) { return obj is Program program && P == program.P; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [WorkItem(25707, "https://github.com/dotnet/roslyn/issues/25707")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogNoSetterOnlyProperty() { var code = @" class Program { public int P => 0; public int S { set { } } [||] }"; var fixedCode = @" class Program { public int P => 0; public int S { set { } } public override bool Equals(object obj) { return obj is Program program && P == program.P; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [WorkItem(41958, "https://github.com/dotnet/roslyn/issues/41958")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestWithDialogInheritedMembers() { var code = @" class Base { public int C { get; set; } } class Middle : Base { public int B { get; set; } } class Derived : Middle { public int A { get; set; } [||] }"; var fixedCode = @" class Base { public int C { get; set; } } class Middle : Base { public int B { get; set; } } class Derived : Middle { public int A { get; set; } public override bool Equals(object obj) { return obj is Derived derived && C == derived.C && B == derived.B && A == derived.A; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators1() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } public static bool operator ==(Program left, Program right) { return EqualityComparer<Program>.Default.Equals(left, right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators2() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { Program program = obj as Program; return program != null && s == program.s; } public static bool operator ==(Program left, Program right) => EqualityComparer<Program>.Default.Equals(left, right); public static bool operator !=(Program left, Program right) => !(left == right); }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators3() { var code = @" using System.Collections.Generic; class Program { public string s; [||] public static bool operator {|CS0216:==|}(Program left, Program right) => true; }"; var fixedCode = @" using System.Collections.Generic; class Program { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } public static bool operator {|CS0216:==|}(Program left, Program right) => true; }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateOperators4() { var code = @" using System.Collections.Generic; struct Program { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; struct Program { public string s; public override bool Equals(object obj) { if (!(obj is Program)) { return false; } var program = (Program)obj; return s == program.s; } public static bool operator ==(Program left, Program right) { return left.Equals(right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGenerateLiftedOperators() { var code = @" using System; using System.Collections.Generic; class Foo { [|public bool? BooleanValue { get; } public decimal? DecimalValue { get; } public Bar? EnumValue { get; } public DateTime? DateTimeValue { get; }|] } enum Bar { }"; var fixedCode = @" using System; using System.Collections.Generic; class Foo { public bool? BooleanValue { get; } public decimal? DecimalValue { get; } public Bar? EnumValue { get; } public DateTime? DateTimeValue { get; } public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && BooleanValue == foo.BooleanValue && DecimalValue == foo.DecimalValue && EnumValue == foo.EnumValue && DateTimeValue == foo.DateTimeValue; } } enum Bar { }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task LiftedOperatorIsNotUsedWhenDirectOperatorWouldNotBeUsed() { var code = @" using System; using System.Collections.Generic; class Foo { [|public Bar Value { get; } public Bar? NullableValue { get; }|] } struct Bar : IEquatable<Bar> { private readonly int value; public override bool Equals(object obj) => false; public bool Equals(Bar other) => value == other.value; public override int GetHashCode() => -1584136870 + value.GetHashCode(); public static bool operator ==(Bar left, Bar right) => left.Equals(right); public static bool operator !=(Bar left, Bar right) => !(left == right); }"; var fixedCode = @" using System; using System.Collections.Generic; class Foo { public Bar Value { get; } public Bar? NullableValue { get; } public override bool Equals(object obj) { var foo = obj as Foo; return foo != null && Value.Equals(foo.Value) && EqualityComparer<Bar?>.Default.Equals(NullableValue, foo.NullableValue); } } struct Bar : IEquatable<Bar> { private readonly int value; public override bool Equals(object obj) => false; public bool Equals(Bar other) => value == other.value; public override int GetHashCode() => -1584136870 + value.GetHashCode(); public static bool operator ==(Bar left, Bar right) => left.Equals(right); public static bool operator !=(Bar left, Bar right) => !(left == right); }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStruct() { var code = @" using System.Collections.Generic; struct Program { public string s; [||] }"; var fixedCode = @" using System; using System.Collections.Generic; struct Program : IEquatable<Program> { public string s; public override bool Equals(object obj) { return obj is Program && Equals((Program)obj); } public bool Equals(Program other) { return s == other.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")] public async Task TestOverrideEqualsOnRefStructReturnsFalse() { var code = @" ref struct Program { public string s; [||] }"; var fixedCode = @" ref struct Program { public string s; public override bool Equals(object obj) { return false; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [WorkItem(25708, "https://github.com/dotnet/roslyn/issues/25708")] public async Task TestImplementIEquatableOnRefStructSkipsIEquatable() { var code = @" ref struct Program { public string s; [||] }"; var fixedCode = @" ref struct Program { public string s; public override bool Equals(object obj) { return false; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, // We are forcefully enabling the ImplementIEquatable option, as that is our way // to test that the option does nothing. The VS mode will ensure if the option // is not available it will not be shown. OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStructInNullableContextWithUnannotatedMetadata() { var code = @"#nullable enable struct Foo { public int Bar { get; } [||] }"; var fixedCode = @"#nullable enable using System; struct Foo : IEquatable<Foo> { public int Bar { get; } public override bool Equals(object? obj) { return obj is Foo foo && Equals(foo); } public bool Equals(Foo other) { return Bar == other.Bar; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnStructInNullableContextWithAnnotatedMetadata() { var code = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; struct Foo { public bool Bar { get; } [||] } "; var fixedCode = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; struct Foo : IEquatable<Foo> { public bool Bar { get; } public override bool Equals(object? obj) { return obj is Foo foo && Equals(foo); } public bool Equals(Foo other) { return Bar == other.Bar; } } "; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClass() { var code = @" using System.Collections.Generic; class Program { public string s; [||] }"; var fixedCode = @" using System; using System.Collections.Generic; class Program : IEquatable<Program> { public string s; public override bool Equals(object obj) { return Equals(obj as Program); } public bool Equals(Program other) { return other != null && s == other.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClassInNullableContextWithUnannotatedMetadata() { var code = @"#nullable enable class Foo { public int Bar { get; } [||] }"; var fixedCode = @"#nullable enable using System; class Foo : IEquatable<Foo?> { public int Bar { get; } public override bool Equals(object? obj) { return Equals(obj as Foo); } public bool Equals(Foo? other) { return other != null && Bar == other.Bar; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestImplementIEquatableOnClassInNullableContextWithAnnotatedMetadata() { var code = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; class Foo { public bool Bar { get; } [||] } "; var fixedCode = @" #nullable enable using System; using System.Diagnostics.CodeAnalysis; class Foo : IEquatable<Foo?> { public bool Bar { get; } public override bool Equals(object? obj) { return Equals(obj as Foo); } public bool Equals(Foo? other) { return other != null && Bar == other.Bar; } } "; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId), LanguageVersion = LanguageVersion.CSharp8, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestDoNotOfferIEquatableIfTypeAlreadyImplementsIt() { var code = @" using System.Collections.Generic; class Program : {|CS0535:System.IEquatable<Program>|} { public string s; [||] }"; var fixedCode = @" using System.Collections.Generic; class Program : {|CS0535:System.IEquatable<Program>|} { public string s; public override bool Equals(object obj) { var program = obj as Program; return program != null && s == program.s; } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => Assert.Null(options.FirstOrDefault(i => i.Id == GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.ImplementIEquatableId)), LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestMissingReferences1() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp6, CodeActionIndex = 1, TestState = { Sources = { @"public class Class1 { [|int i;|] public void F() { } }", }, ExpectedDiagnostics = { // /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"), // /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"), // /0/Test0.cs(5,12): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 12, 5, 16).WithArguments("System.Void"), }, }, FixedState = { Sources = { @"public class Class1 { int i; public override System.Boolean Equals(System.Object obj) { Class1 @class = obj as Class1; return @class != null && i == @class.i; } public void F() { } public override System.Int32 GetHashCode() { return 165851236 + EqualityComparer<System.Int32>.Default.GetHashCode(i); } }", }, ExpectedDiagnostics = { // /0/Test0.cs(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(1, 14, 1, 20).WithArguments("System.Object"), // /0/Test0.cs(1,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments DiagnosticResult.CompilerError("CS1729").WithSpan(1, 14, 1, 20).WithArguments("object", "0"), // /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(3, 5, 3, 8).WithArguments("System.Int32"), // /0/Test0.cs(5,21): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 21, 5, 27).WithArguments("System.Object"), // /0/Test0.cs(5,28): error CS1069: The type name 'Boolean' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(5, 28, 5, 35).WithArguments("Boolean", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(5, 43, 5, 49).WithArguments("System.Object"), // /0/Test0.cs(5,50): error CS1069: The type name 'Object' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(5, 50, 5, 56).WithArguments("Object", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(7,9): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(7, 9, 7, 15).WithArguments("System.Object"), // /0/Test0.cs(7,32): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(7, 32, 7, 38).WithArguments("System.Object"), // /0/Test0.cs(8,16): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(8, 16, 8, 30).WithArguments("System.Object"), // /0/Test0.cs(9,16): error CS0518: Predefined type 'System.Boolean' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(9, 16, 9, 29).WithArguments("System.Boolean"), // /0/Test0.cs(12,12): error CS0518: Predefined type 'System.Void' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(12, 12, 12, 16).WithArguments("System.Void"), // /0/Test0.cs(16,21): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(16, 21, 16, 27).WithArguments("System.Object"), // /0/Test0.cs(16,28): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(16, 28, 16, 33).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), // /0/Test0.cs(16,34): error CS0115: 'Class1.GetHashCode()': no suitable method found to override DiagnosticResult.CompilerError("CS0115").WithSpan(16, 34, 16, 45).WithArguments("Class1.GetHashCode()"), // /0/Test0.cs(18,16): error CS0518: Predefined type 'System.Int32' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 16, 18, 25).WithArguments("System.Int32"), // /0/Test0.cs(18,28): error CS0103: The name 'EqualityComparer' does not exist in the current context DiagnosticResult.CompilerError("CS0103").WithSpan(18, 28, 18, 58).WithArguments("EqualityComparer"), // /0/Test0.cs(18,28): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 28, 18, 58).WithArguments("System.Object"), // /0/Test0.cs(18,45): error CS0518: Predefined type 'System.Object' is not defined or imported DiagnosticResult.CompilerError("CS0518").WithSpan(18, 45, 18, 51).WithArguments("System.Object"), // /0/Test0.cs(18,52): error CS1069: The type name 'Int32' could not be found in the namespace 'System'. This type has been forwarded to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Consider adding a reference to that assembly. DiagnosticResult.CompilerError("CS1069").WithSpan(18, 52, 18, 57).WithArguments("Int32", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), }, }, ReferenceAssemblies = ReferenceAssemblies.Default.WithAssemblies(ImmutableArray<string>.Empty), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeInCheckedContext() { var code = @"using System.Collections.Generic; class Program { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Program { int i; string S { get; } public override bool Equals(object obj) { Program program = obj as Program; return program != null && i == program.i && S == program.S; } public override int GetHashCode() { unchecked { int hashCode = -538000506; hashCode = hashCode * -1521134295 + i.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(S); return hashCode; } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, SolutionTransforms = { (solution, projectId) => { var compilationOptions = solution.GetRequiredProject(projectId).CompilationOptions; return solution.WithProjectCompilationOptions(projectId, compilationOptions.WithOverflowChecks(true)); }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeStruct() { var code = @"using System.Collections.Generic; struct S { [|int j;|] }"; var fixedCode = @"using System; using System.Collections.Generic; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeOneMember() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { } } struct S { [|int j;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { } } struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return HashCode.Combine(j); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(21,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(21, 25, 21, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPublicSystemHashCodeOtherProject() { var publicHashCode = @"using System.Collections.Generic; namespace System { public struct HashCode { } }"; var code = @"struct S { [|int j;|] }"; var fixedCode = @"using System; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return HashCode.Combine(j); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestState = { AdditionalProjects = { ["P1"] = { Sources = { ("HashCode.cs", publicHashCode) }, }, }, Sources = { code }, AdditionalProjectReferences = { "P1" }, }, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(19,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(19, 25, 19, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(37297, "https://github.com/dotnet/roslyn/issues/37297")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestInternalSystemHashCode() { var internalHashCode = @"using System.Collections.Generic; namespace System { internal struct HashCode { } }"; var code = @"struct S { [|int j;|] }"; var fixedCode = @"using System; struct S : IEquatable<S> { int j; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j; } public override int GetHashCode() { return 1424088837 + j.GetHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestState = { AdditionalProjects = { ["P1"] = { Sources = { ("HashCode.cs", internalHashCode) }, }, }, Sources = { code }, AdditionalProjectReferences = { "P1" }, }, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeEightMembers() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { } } struct S { [|int j, k, l, m, n, o, p, q;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q; } public override int GetHashCode() { return HashCode.Combine(j, k, l, m, n, o, p, q); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(28,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(28, 25, 28, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeNineMembers() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S { [|int j, k, l, m, n, o, p, q, r;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q, r; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q && r == other.r; } public override int GetHashCode() { var hash = new HashCode(); hash.Add(j); hash.Add(k); hash.Add(l); hash.Add(m); hash.Add(n); hash.Add(o); hash.Add(p); hash.Add(q); hash.Add(r); return hash.ToHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSystemHashCodeNineMembers_Explicit() { var code = @"using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S { [|int j, k, l, m, n, o, p, q, r;|] }"; var fixedCode = @"using System; using System.Collections.Generic; namespace System { public struct HashCode { public void Add<T>(T value) { } public int ToHashCode() => 0; } } struct S : IEquatable<S> { int j, k, l, m, n, o, p, q, r; public override bool Equals(object obj) { return obj is S && Equals((S)obj); } public bool Equals(S other) { return j == other.j && k == other.k && l == other.l && m == other.m && n == other.n && o == other.o && p == other.p && q == other.q && r == other.r; } public override int GetHashCode() { HashCode hash = new HashCode(); hash.Add(j); hash.Add(k); hash.Add(l); hash.Add(m); hash.Add(n); hash.Add(o); hash.Add(p); hash.Add(q); hash.Add(r); return hash.ToHashCode(); } public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 1, LanguageVersion = LanguageVersion.CSharp6, Options = { PreferExplicitTypeWithInfo() }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField_Patterns() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; class Program { [|int a;|] }", @"using System.Collections.Generic; class Program { int a; public override bool Equals(object obj) { return obj is Program program && a == program.a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleFieldInStruct_Patterns() { await VerifyCS.VerifyRefactoringAsync( @"using System.Collections.Generic; struct Program { [|int a;|] }", @"using System; using System.Collections.Generic; struct Program : IEquatable<Program> { int a; public override bool Equals(object obj) { return obj is Program program && Equals(program); } public bool Equals(Program other) { return a == other.a; } public static bool operator ==(Program left, Program right) { return left.Equals(right); } public static bool operator !=(Program left, Program right) { return !(left == right); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseWithOverriddenEquals_Patterns() { var code = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { [|int i; string S { get; }|] }"; var fixedCode = @"using System.Collections.Generic; class Base { public override bool Equals(object o) { return false; } } class Program : Base { int i; string S { get; } public override bool Equals(object obj) { return obj is Program program && base.Equals(obj) && i == program.i && S == program.S; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionIndex = 0, }.RunAsync(); } [WorkItem(33601, "https://github.com/dotnet/roslyn/issues/33601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialSelection() { var code = @"using System.Collections.Generic; class Program { int [|a|]; }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, }.RunAsync(); } [WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualityOperatorsNullableAnnotationWithReferenceType() { var code = @" #nullable enable using System; namespace N { public class C[||] { public int X; } }"; var fixedCode = @" #nullable enable using System; using System.Collections.Generic; namespace N { public class C { public int X; public override bool Equals(object? obj) { return obj is C c && X == c.X; } public static bool operator ==(C? left, C? right) { return EqualityComparer<C>.Default.Equals(left, right); } public static bool operator !=(C? left, C? right) { return !(left == right); } } }"; await new TestWithDialog { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(20,55): error CS8604: Possible null reference argument for parameter 'x' in 'bool EqualityComparer<C>.Equals(C x, C y)'. DiagnosticResult.CompilerError("CS8604").WithSpan(20, 55, 20, 59).WithArguments("x", "bool EqualityComparer<C>.Equals(C x, C y)"), // /0/Test0.cs(20,61): error CS8604: Possible null reference argument for parameter 'y' in 'bool EqualityComparer<C>.Equals(C x, C y)'. DiagnosticResult.CompilerError("CS8604").WithSpan(20, 61, 20, 66).WithArguments("y", "bool EqualityComparer<C>.Equals(C x, C y)"), }, }, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.Default, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(40053, "https://github.com/dotnet/roslyn/issues/40053")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualityOperatorsNullableAnnotationWithValueType() { var code = @" #nullable enable using System; namespace N { public struct C[||] { public int X; } }"; var fixedCode = @" #nullable enable using System; namespace N { public struct C { public int X; public override bool Equals(object? obj) { return obj is C c && X == c.X; } public static bool operator ==(C left, C right) { return left.Equals(right); } public static bool operator !=(C left, C right) { return !(left == right); } } }"; await new TestWithDialog { TestCode = code, FixedCode = fixedCode, MemberNames = default, OptionsCallback = options => EnableOption(options, GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.GenerateOperatorsId), LanguageVersion = LanguageVersion.Default, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes1() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { int bar; [||] }", @"partial class Goo { }", }, }, FixedState = { Sources = { @"partial class Goo { int bar; public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", @"partial class Goo { }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes2() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { int bar; }", @"partial class Goo { [||] }", }, }, FixedState = { Sources = { @"partial class Goo { int bar; }", @"partial class Goo { public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes3() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { [||] }", @"partial class Goo { int bar; }", }, }, FixedState = { Sources = { @"partial class Goo { public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", @"partial class Goo { int bar; }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(42574, "https://github.com/dotnet/roslyn/issues/42574")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestPartialTypes4() { await new TestWithDialog { TestState = { Sources = { @"partial class Goo { }", @"partial class Goo { int bar; [||] }", }, }, FixedState = { Sources = { @"partial class Goo { }", @"partial class Goo { int bar; public override bool Equals(object obj) { return obj is Goo goo && bar == goo.bar; } public override int GetHashCode() { return 999205674 + bar.GetHashCode(); } }", }, }, MemberNames = ImmutableArray.Create("bar"), CodeActionIndex = 1, }.RunAsync(); } [WorkItem(43290, "https://github.com/dotnet/roslyn/issues/43290")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestAbstractBase() { var code = @" #nullable enable namespace System { public struct HashCode { } } abstract class Base { public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); } class {|CS0534:{|CS0534:Derived|}|} : Base { [|public int P { get; }|] }"; var fixedCode = @" #nullable enable using System; namespace System { public struct HashCode { } } abstract class Base { public abstract override bool Equals(object? obj); public abstract override int GetHashCode(); } class Derived : Base { public int P { get; } public override bool Equals(object? obj) { return obj is Derived derived && P == derived.P; } public override int GetHashCode() { return HashCode.Combine(P); } }"; await new VerifyCS.Test { TestCode = code, FixedState = { Sources = { fixedCode }, ExpectedDiagnostics = { // /0/Test0.cs(23,25): error CS0117: 'HashCode' does not contain a definition for 'Combine' DiagnosticResult.CompilerError("CS0117").WithSpan(26, 25, 26, 32).WithArguments("System.HashCode", "Combine"), }, }, CodeActionIndex = 1, LanguageVersion = LanguageVersion.Default, }.RunAsync(); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/Core/Portable/Diagnostics/DocumentDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// IDE-only document based diagnostic analyzer. /// </summary> internal abstract class DocumentDiagnosticAnalyzer : DiagnosticAnalyzer { public const int DefaultPriority = 50; public abstract Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken); public abstract Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken); /// <summary> /// it is not allowed one to implement both DocumentDiagnosticAnalzyer and DiagnosticAnalyzer /// </summary> #pragma warning disable RS1026 // Enable concurrent execution #pragma warning disable RS1025 // Configure generated code analysis public sealed override void Initialize(AnalysisContext context) #pragma warning restore RS1025 // Configure generated code analysis #pragma warning restore RS1026 // Enable concurrent execution { } /// <summary> /// This lets vsix installed <see cref="DocumentDiagnosticAnalyzer"/> or <see cref="ProjectDiagnosticAnalyzer"/> to /// specify priority of the analyzer. Regular <see cref="DiagnosticAnalyzer"/> always comes before those 2 different types. /// Priority is ascending order and this only works on HostDiagnosticAnalyzer meaning Vsix installed analyzers in VS. /// This is to support partner teams (such as typescript and F#) who want to order their analyzer's execution order. /// </summary> public virtual int Priority => DefaultPriority; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// IDE-only document based diagnostic analyzer. /// </summary> internal abstract class DocumentDiagnosticAnalyzer : DiagnosticAnalyzer { public const int DefaultPriority = 50; public abstract Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken); public abstract Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken); /// <summary> /// it is not allowed one to implement both DocumentDiagnosticAnalzyer and DiagnosticAnalyzer /// </summary> #pragma warning disable RS1026 // Enable concurrent execution #pragma warning disable RS1025 // Configure generated code analysis public sealed override void Initialize(AnalysisContext context) #pragma warning restore RS1025 // Configure generated code analysis #pragma warning restore RS1026 // Enable concurrent execution { } /// <summary> /// This lets vsix installed <see cref="DocumentDiagnosticAnalyzer"/> or <see cref="ProjectDiagnosticAnalyzer"/> to /// specify priority of the analyzer. Regular <see cref="DiagnosticAnalyzer"/> always comes before those 2 different types. /// Priority is ascending order and this only works on HostDiagnosticAnalyzer meaning Vsix installed analyzers in VS. /// This is to support partner teams (such as typescript and F#) who want to order their analyzer's execution order. /// </summary> public virtual int Priority => DefaultPriority; } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/EditorFeatures/Core/Implementation/InlineRename/RenameTrackingSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal struct RenameTrackingSpan { public readonly ITrackingSpan TrackingSpan; public readonly RenameSpanKind Type; public RenameTrackingSpan(ITrackingSpan trackingSpan, RenameSpanKind type) { this.TrackingSpan = trackingSpan; this.Type = type; } } internal enum RenameSpanKind { None, Reference, UnresolvedConflict, Complexified } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal struct RenameTrackingSpan { public readonly ITrackingSpan TrackingSpan; public readonly RenameSpanKind Type; public RenameTrackingSpan(ITrackingSpan trackingSpan, RenameSpanKind type) { this.TrackingSpan = trackingSpan; this.Type = type; } } internal enum RenameSpanKind { None, Reference, UnresolvedConflict, Complexified } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Features/Core/Portable/Notification/INotificationServiceCallback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Notification { internal interface INotificationServiceCallback { Action<string, string, NotificationSeverity> NotificationCallback { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Notification { internal interface INotificationServiceCallback { Action<string, string, NotificationSeverity> NotificationCallback { get; set; } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelNavigationPointServiceFactory.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel <ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService ' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it Return provider.GetService(Of ICodeModelService) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel <ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService ' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it Return provider.GetService(Of ICodeModelService) End Function End Class End Namespace
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IForEachLoopStatement.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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_SimpleForLoopsTest() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr'BIND:"For Each s As String In arr" Console.WriteLine(s) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next') Locals: Local_1: s As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String') Initializer: null Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithList() Dim source = <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim list As New System.Collections.Generic.List(Of String)() list.Add("a") list.Add("b") list.Add("c") For Each item As String In list'BIND:"For Each item As String In list" System.Console.WriteLine(item) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each it ... Next') Locals: Local_1: item As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: item As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'item As String') Initializer: null Collection: ILocalReferenceOperation: list (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'list') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each it ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(item)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item') ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithBreak() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x'BIND:"For Each y As Char In x" If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c') Left: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') WhenFalse: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Else ... riteLine(y)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithContinue() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S'BIND:"For Each x As String In S" For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next y, x') Locals: Local_1: x As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String') Initializer: null Collection: ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next y, x') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next y, x') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next y, x') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c') Left: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If') IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'Continue For') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(2): ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Nested() Dim source = <![CDATA[ Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x'BIND:"For Each y As Integer In x" System.Console.WriteLine(y) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Integer') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Nested1() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S'BIND:"For Each x As String In S" For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String') Initializer: null Collection: ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Interface() Dim source = <![CDATA[ Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_String() Dim source = <![CDATA[ Option Infer On Class Program Public Shared Sub Main() Const s As String = Nothing For Each y In s'BIND:"For Each y In s" System.Console.WriteLine(y) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Collection: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String, Constant: null) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_IterateStruct() Dim source = <![CDATA[ Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_QueryExpression() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Module Program Sub Main(args As String()) ' Obtain a list of customers. Dim customers As List(Of Customer) = GetCustomers() ' Return customers that are grouped based on country. Dim countries = From cust In customers Order By cust.Country, cust.City Group By CountryName = cust.Country Into CustomersInCountry = Group, Count() Order By CountryName ' Output the results. For Each country In countries'BIND:"For Each country In countries" Debug.WriteLine(country.CountryName & " count=" & country.Count) For Each customer In country.CustomersInCountry Debug.WriteLine(" " & customer.CompanyName & " " & customer.City) Next Next End Sub Private Function GetCustomers() As List(Of Customer) Return New List(Of Customer) From { New Customer With {.CustomerID = 1, .CompanyName = "C", .City = "H", .Country = "C"}, New Customer With {.CustomerID = 2, .CompanyName = "M", .City = "R", .Country = "U"}, New Customer With {.CustomerID = 3, .CompanyName = "F", .City = "V", .Country = "C"} } End Function End Module Class Customer Public Property CustomerID As Integer Public Property CompanyName As String Public Property City As String Public Property Country As String End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each co ... Next') Locals: Local_1: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32> LoopControlVariable: IVariableDeclaratorOperation (Symbol: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'country') Initializer: null Collection: ILocalReferenceOperation: countries (OperationKind.LocalReference, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>)) (Syntax: 'countries') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each co ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... ntry.Count)') Expression: IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... ntry.Count)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'country.Cou ... untry.Count') IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... untry.Count') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... & " count="') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CountryName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'country.CountryName') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " count=") (Syntax: '" count="') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'country.Count') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'country.Count') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each cu ... Next') Locals: Local_1: customer As Customer LoopControlVariable: IVariableDeclaratorOperation (Symbol: customer As Customer) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'customer') Initializer: null Collection: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of Customer)) (Syntax: 'country.Cus ... rsInCountry') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each cu ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... tomer.City)') Expression: IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... tomer.City)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: '" " & cus ... stomer.City') IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... stomer.City') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... Name & " "') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... CompanyName') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') Right: IPropertyReferenceOperation: Property Customer.CompanyName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.CompanyName') Instance Receiver: ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') Right: IPropertyReferenceOperation: Property Customer.City As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.City') Instance Receiver: ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Multidimensional() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k'BIND:"For Each [Custom] In k" Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each [C ... Next') Locals: Local_1: Custom As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: Custom As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: '[Custom]') Initializer: null Collection: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32(,)) (Syntax: 'k') Body: IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each [C ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... (Integer)))') Expression: IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (Integer)))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... e(Integer))') IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... e(Integer))') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]') ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Integer)') ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)') TypeOperand: System.Int32 InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... e(Object)))') Expression: IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... e(Object)))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... pe(Object))') IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... pe(Object))') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]') ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Object)') ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Object)') TypeOperand: System.Object InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_LateBinding() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o'BIND:"For Each x In o" Console.WriteLine(x) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'o') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Pattern() Dim source = <![CDATA[ Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) & lt; 4 End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Lambda() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Class C1 Private element_lambda_field As Integer Public Shared Sub Main() Dim c1 As New C1() c1.DoStuff() End Sub Public Sub DoStuff() Dim arr As Integer() = New Integer(1) {} arr(0) = 23 arr(1) = 42 Dim myDelegate As Action = Sub() Dim element_lambda_local As Integer For Each element_lambda_local In arr'BIND:"For Each element_lambda_local In arr" Console.WriteLine(element_lambda_local) Next element_lambda_local End Sub myDelegate.Invoke() End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each el ... ambda_local') LoopControlVariable: ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'arr') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each el ... ambda_local') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... mbda_local)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... mbda_local)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element_lambda_local') ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(1): ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_InvalidConversion() Dim source = <![CDATA[ Imports System Class C1 Public Shared Sub Main() For Each element As Integer In "Hello World."'BIND:"For Each element As Integer In "Hello World."" Console.WriteLine(element) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each el ... Next') Locals: Local_1: element As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: element As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element As Integer') Initializer: null Collection: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World.", IsInvalid) (Syntax: '"Hello World."') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each el ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... ne(element)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ne(element)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element') ILocalReferenceOperation: element (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Throw() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr'BIND:"For Each s As String In arr" If (s = "one") Then Throw New Exception End If Console.WriteLine(s) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next') Locals: Local_1: s As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String') Initializer: null Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If (s = "on ... End If') Condition: IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Boolean) (Syntax: '(s = "one")') Operand: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's = "one"') Left: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "one") (Syntax: '"one"') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If (s = "on ... End If') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw New Exception') IObjectCreationOperation (Constructor: Sub System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'New Exception') Arguments(0) Initializer: null WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithReturn() Dim source = <![CDATA[ Class C Private F As Object Shared Function M(c As Object()) As Boolean For Each o In c'BIND:"For Each o In c" If o IsNot Nothing Then Return True Next Return False End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each o ... Next') Locals: Local_1: o As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: o As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'o') Initializer: null Collection: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Object()) (Syntax: 'c') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each o ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If o IsNot ... Return True') Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'o IsNot Nothing') Left: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If o IsNot ... Return True') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') WhenFalse: null NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_FieldAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(args As Integer()) For Each X In args'BIND:"For Each X In args" Next X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each X ... Next X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each X ... Next X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_FieldWithExplicitReceiverAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(c As C, args As Integer()) For Each c.X In args'BIND:"For Each c.X In args" Next c.X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each c. ... Next c.X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each c. ... Next c.X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_CastArrayToIEnumerable() Dim source = <![CDATA[ Option Infer On Imports System.Collections Class Program Public Shared Sub Main(args As String(), i As String) For Each arg As String In DirectCast(args, IEnumerable)'BIND:"For Each arg As String In DirectCast(args, IEnumerable)" i = arg Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next') Locals: Local_1: arg As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable) (Syntax: 'DirectCast( ... Enumerable)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i') Right: ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_CastCollectionToIEnumerable() Dim source = <![CDATA[ Option Infer On Imports System.Collections.Generic Class Program Public Shared Sub Main(args As List(Of String), i As String) For Each arg As String In DirectCast(args, IEnumerable(Of String))'BIND:"For Each arg As String In DirectCast(args, IEnumerable(Of String))" i = arg Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next') Locals: Local_1: arg As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'DirectCast( ... Of String))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'args') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i') Right: ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_InvalidLoopControlVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Sub M(args As Integer()) Dim i as Integer = 0 For Each i as Integer In args'BIND:"For Each i as Integer In args" Next i End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each i ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer') Initializer: null Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each i ... Next i') NextVariables(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'i' hides a variable in an enclosing block. For Each i as Integer In args'BIND:"For Each i as Integer In args" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_01() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C(), y as C(), result As C) 'BIND:"Sub M" For Each z in If(x, y) result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C()) (Syntax: 'x') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C()) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(x, y)') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'If(x, y)') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(x, y)') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') Arguments(0) Leaving: {R1} Next (Regular) Block[B6] Entering: {R4} .locals {R4} { Locals: [z As C] Block[B6] - Block Predecessors: [B5] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'z') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'z') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: C) (Syntax: 'z') Next (Regular) Block[B5] Leaving: {R4} } } Block[B7] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_02() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As String) 'BIND:"Sub M" For Each z As String in x z?.ToString() Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.String.GetEnumerator() As System.CharEnumerator) (OperationKind.Invocation, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B4] [B5] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation ( Function System.CharEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R6} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.String] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As String') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'z As String') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'z As String') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningString) Operand: IPropertyReferenceOperation: ReadOnly Property System.CharEnumerator.Current As System.Char (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'z As String') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.String) (Syntax: 'z') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z') Leaving: {R5} {R4} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'z?.ToString()') Expression: IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z') Arguments(0) Next (Regular) Block[B2] Leaving: {R5} {R4} } } } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_03() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer(,), result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_04() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Enumerable, result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class Public Structure Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Structure Public Structure Enumerator Public ReadOnly Property Current As Integer Get Return 1 End Get End Property Public Function MoveNext() As Boolean Return False End Function End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_05() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Enumerable, result As Integer) 'BIND:"Sub M" For Each z As Integer in x result = z Next End Sub End Class Public Structure Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Structure Public Structure Enumerator Implements System.IDisposable Public ReadOnly Property Current As Integer Get Return 1 End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Function MoveNext() As Boolean Return False End Function End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Integer') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer') Right: IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B5] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_06() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As System.Collections.Generic.IEnumerable(Of Integer), result As Integer) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32)) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_11() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Object, result As Object) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { CaptureIds: [1] Block[B4] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_12() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C, result As Integer) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32023: Expression is of type 'C', which is not a collection type. For Each z in x ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(0) Next (Regular) Block[B3] Entering: {R1} .locals {R1} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_15() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M() 'BIND:"Sub M" For Each If(GetC(), Me).F in Me Next End Sub Public F As C Public ReadOnly Property Current As C Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class Module Ext <Runtime.CompilerServices.Extension> Public Function GetEnumerator(this As C) As C Return this End Function End Module ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()') Value: IInvocationOperation (Function C.GetC() As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetC()') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()') Leaving: {R3} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()') Next (Regular) Block[B6] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F') Left: IFieldReferenceOperation: C.F As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(GetC(), Me).F') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me)') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Next (Regular) Block[B2] Leaving: {R2} } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_16() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As System.Collections.IEnumerable, result As Object) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { CaptureIds: [1] Block[B4] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_17() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer(), result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_18() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Boolean) 'BIND:"Sub M" For Each x in Me If x Continue For End If result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] [B4] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B4] ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B5] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_19() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Boolean) 'BIND:"Sub M" For Each x in Me If x Exit For End If result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B4] ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R2} {R1} Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_20() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M" For Each x in Me While y result = y Continue For End While result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] [B5] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_21() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M" For Each x in Me While y result = y Exit For End While result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B6] Leaving: {R2} {R1} Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B6] - Exit Predecessors: [B2] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_22() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" For Each z As Long in If(GetC(), GetC()) Next End Sub Shared Function GetC() As C Return Nothing End Function Shared Function GetEnumerator() As C Return Nothing End Function Shared Function MoveNext() As Boolean Return Nothing End Function Shared ReadOnly Property Current As Integer Get Return 1 End Get End Property End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(GetC(), GetC())') Value: IInvocationOperation (Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'If(GetC(), GetC())') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(GetC(), GetC())') Instance Receiver: null Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Instance Receiver: null Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_23() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C) 'BIND:"Sub M" For Each z in x Next End Sub Function GetEnumerator(<System.Runtime.CompilerServices.CallerMemberName> Optional member As String = "") As C Return Nothing End Function Function MoveNext(Optional s As String = "ABC") As Boolean Return Nothing End Function ReadOnly Property Current(Optional d As Double = 123.45) As Integer Get Return 1 End Get End Property End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function C.GetEnumerator([member As System.String = ""]) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: member) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "M", IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext([s As System.String = "ABC"]) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "ABC", IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property C.Current([d As System.Double = 123.45]) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: d) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 123.45, IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, useLatestFramework:=True) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_24() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Integer) 'BIND:"Sub M" For Each x As Integer in GetC(x) result = x Next End Sub Public Function GetC(ByRef x as Integer) As C Return Me End Function Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Integer Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { Locals: [x As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC(x)') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'GetC(x)') Instance Receiver: IInvocationOperation ( Function C.GetC(ByRef x As System.Int32) As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC(x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'GetC') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Arguments(0) Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'GetC(x)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { Locals: [x As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As Integer') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R3} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_25() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as C) 'BIND:"Sub M" For Each x As C in x result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As C Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. For Each x As C in x ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { Locals: [x As C] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { Locals: [x As C] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As C') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'x As C') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'x As C') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R3} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_SimpleForLoopsTest() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr'BIND:"For Each s As String In arr" Console.WriteLine(s) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next') Locals: Local_1: s As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String') Initializer: null Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithList() Dim source = <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim list As New System.Collections.Generic.List(Of String)() list.Add("a") list.Add("b") list.Add("c") For Each item As String In list'BIND:"For Each item As String In list" System.Console.WriteLine(item) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each it ... Next') Locals: Local_1: item As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: item As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'item As String') Initializer: null Collection: ILocalReferenceOperation: list (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'list') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each it ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(item)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item') ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithBreak() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x'BIND:"For Each y As Char In x" If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c') Left: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') WhenFalse: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Else ... riteLine(y)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithContinue() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S'BIND:"For Each x As String In S" For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next y, x') Locals: Local_1: x As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String') Initializer: null Collection: ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next y, x') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next y, x') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next y, x') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If') Condition: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c') Left: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If') IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'Continue For') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(2): ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Nested() Dim source = <![CDATA[ Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x'BIND:"For Each y As Integer In x" System.Console.WriteLine(y) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Integer') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Nested1() Dim source = <![CDATA[ Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S'BIND:"For Each x As String In S" For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String') Initializer: null Collection: ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char') Initializer: null Collection: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Interface() Dim source = <![CDATA[ Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_String() Dim source = <![CDATA[ Option Infer On Class Program Public Shared Sub Main() Const s As String = Nothing For Each y In s'BIND:"For Each y In s" System.Console.WriteLine(y) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next') Locals: Local_1: y As System.Char LoopControlVariable: IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y') Initializer: null Collection: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String, Constant: null) (Syntax: 's') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_IterateStruct() Dim source = <![CDATA[ Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_QueryExpression() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Module Program Sub Main(args As String()) ' Obtain a list of customers. Dim customers As List(Of Customer) = GetCustomers() ' Return customers that are grouped based on country. Dim countries = From cust In customers Order By cust.Country, cust.City Group By CountryName = cust.Country Into CustomersInCountry = Group, Count() Order By CountryName ' Output the results. For Each country In countries'BIND:"For Each country In countries" Debug.WriteLine(country.CountryName & " count=" & country.Count) For Each customer In country.CustomersInCountry Debug.WriteLine(" " & customer.CompanyName & " " & customer.City) Next Next End Sub Private Function GetCustomers() As List(Of Customer) Return New List(Of Customer) From { New Customer With {.CustomerID = 1, .CompanyName = "C", .City = "H", .Country = "C"}, New Customer With {.CustomerID = 2, .CompanyName = "M", .City = "R", .Country = "U"}, New Customer With {.CustomerID = 3, .CompanyName = "F", .City = "V", .Country = "C"} } End Function End Module Class Customer Public Property CustomerID As Integer Public Property CompanyName As String Public Property City As String Public Property Country As String End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each co ... Next') Locals: Local_1: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32> LoopControlVariable: IVariableDeclaratorOperation (Symbol: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'country') Initializer: null Collection: ILocalReferenceOperation: countries (OperationKind.LocalReference, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>)) (Syntax: 'countries') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each co ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... ntry.Count)') Expression: IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... ntry.Count)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'country.Cou ... untry.Count') IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... untry.Count') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... & " count="') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CountryName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'country.CountryName') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " count=") (Syntax: '" count="') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'country.Count') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'country.Count') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each cu ... Next') Locals: Local_1: customer As Customer LoopControlVariable: IVariableDeclaratorOperation (Symbol: customer As Customer) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'customer') Initializer: null Collection: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of Customer)) (Syntax: 'country.Cus ... rsInCountry') Instance Receiver: ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each cu ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... tomer.City)') Expression: IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... tomer.City)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: '" " & cus ... stomer.City') IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... stomer.City') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... Name & " "') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... CompanyName') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') Right: IPropertyReferenceOperation: Property Customer.CompanyName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.CompanyName') Instance Receiver: ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') Right: IPropertyReferenceOperation: Property Customer.City As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.City') Instance Receiver: ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Multidimensional() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k'BIND:"For Each [Custom] In k" Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each [C ... Next') Locals: Local_1: Custom As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: Custom As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: '[Custom]') Initializer: null Collection: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32(,)) (Syntax: 'k') Body: IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each [C ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... (Integer)))') Expression: IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (Integer)))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... e(Integer))') IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... e(Integer))') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]') ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Integer)') ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)') TypeOperand: System.Int32 InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... e(Object)))') Expression: IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... e(Object)))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... pe(Object))') IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... pe(Object))') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]') ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Object)') ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Object)') TypeOperand: System.Object InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For') NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_LateBinding() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o'BIND:"For Each x In o" Console.WriteLine(x) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'o') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Pattern() Dim source = <![CDATA[ Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()" System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) & lt; 4 End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next') Locals: Local_1: x As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x') Initializer: null Collection: IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Lambda() Dim source = <![CDATA[ Option Strict On Option Infer On Imports System Class C1 Private element_lambda_field As Integer Public Shared Sub Main() Dim c1 As New C1() c1.DoStuff() End Sub Public Sub DoStuff() Dim arr As Integer() = New Integer(1) {} arr(0) = 23 arr(1) = 42 Dim myDelegate As Action = Sub() Dim element_lambda_local As Integer For Each element_lambda_local In arr'BIND:"For Each element_lambda_local In arr" Console.WriteLine(element_lambda_local) Next element_lambda_local End Sub myDelegate.Invoke() End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each el ... ambda_local') LoopControlVariable: ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'arr') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each el ... ambda_local') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... mbda_local)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... mbda_local)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element_lambda_local') ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(1): ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local') ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_InvalidConversion() Dim source = <![CDATA[ Imports System Class C1 Public Shared Sub Main() For Each element As Integer In "Hello World."'BIND:"For Each element As Integer In "Hello World."" Console.WriteLine(element) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each el ... Next') Locals: Local_1: element As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: element As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element As Integer') Initializer: null Collection: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World.", IsInvalid) (Syntax: '"Hello World."') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each el ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... ne(element)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ne(element)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element') ILocalReferenceOperation: element (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_Throw() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr'BIND:"For Each s As String In arr" If (s = "one") Then Throw New Exception End If Console.WriteLine(s) Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next') Locals: Local_1: s As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String') Initializer: null Collection: ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If (s = "on ... End If') Condition: IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Boolean) (Syntax: '(s = "one")') Operand: IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's = "one"') Left: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "one") (Syntax: '"one"') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If (s = "on ... End If') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw New Exception') IObjectCreationOperation (Constructor: Sub System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'New Exception') Arguments(0) Initializer: null WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_WithReturn() Dim source = <![CDATA[ Class C Private F As Object Shared Function M(c As Object()) As Boolean For Each o In c'BIND:"For Each o In c" If o IsNot Nothing Then Return True Next Return False End Function End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each o ... Next') Locals: Local_1: o As System.Object LoopControlVariable: IVariableDeclaratorOperation (Symbol: o As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'o') Initializer: null Collection: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Object()) (Syntax: 'c') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each o ... Next') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If o IsNot ... Return True') Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'o IsNot Nothing') Left: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') WhenTrue: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If o IsNot ... Return True') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True') ReturnedValue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True') WhenFalse: null NextVariables(0) ]]>.Value VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_FieldAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(args As Integer()) For Each X In args'BIND:"For Each X In args" Next X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each X ... Next X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each X ... Next X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_FieldWithExplicitReceiverAsIterationVariable() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Private X As Integer = 0 Sub M(c As C, args As Integer()) For Each c.X In args'BIND:"For Each c.X In args" Next c.X End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each c. ... Next c.X') LoopControlVariable: IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each c. ... Next c.X') NextVariables(1): IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_CastArrayToIEnumerable() Dim source = <![CDATA[ Option Infer On Imports System.Collections Class Program Public Shared Sub Main(args As String(), i As String) For Each arg As String In DirectCast(args, IEnumerable)'BIND:"For Each arg As String In DirectCast(args, IEnumerable)" i = arg Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next') Locals: Local_1: arg As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable) (Syntax: 'DirectCast( ... Enumerable)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i') Right: ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_CastCollectionToIEnumerable() Dim source = <![CDATA[ Option Infer On Imports System.Collections.Generic Class Program Public Shared Sub Main(args As List(Of String), i As String) For Each arg As String In DirectCast(args, IEnumerable(Of String))'BIND:"For Each arg As String In DirectCast(args, IEnumerable(Of String))" i = arg Next End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next') Locals: Local_1: arg As System.String LoopControlVariable: IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'DirectCast( ... Of String))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'args') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i') Right: ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg') NextVariables(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")> Public Sub IForEachLoopStatement_InvalidLoopControlVariableDeclaration() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Class C Sub M(args As Integer()) Dim i as Integer = 0 For Each i as Integer In args'BIND:"For Each i as Integer In args" Next i End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each i ... Next i') Locals: Local_1: i As System.Int32 LoopControlVariable: IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer') Initializer: null Collection: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each i ... Next i') NextVariables(1): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'i' hides a variable in an enclosing block. For Each i as Integer In args'BIND:"For Each i as Integer In args" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_01() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C(), y as C(), result As C) 'BIND:"Sub M" For Each z in If(x, y) result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C()) (Syntax: 'x') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C()) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(x, y)') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'If(x, y)') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(x, y)') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') Arguments(0) Leaving: {R1} Next (Regular) Block[B6] Entering: {R4} .locals {R4} { Locals: [z As C] Block[B6] - Block Predecessors: [B5] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'z') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'z') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: C) (Syntax: 'z') Next (Regular) Block[B5] Leaving: {R4} } } Block[B7] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_02() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As String) 'BIND:"Sub M" For Each z As String in x z?.ToString() Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.String.GetEnumerator() As System.CharEnumerator) (OperationKind.Invocation, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B4] [B5] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation ( Function System.CharEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R6} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.String] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As String') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'z As String') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'z As String') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningString) Operand: IPropertyReferenceOperation: ReadOnly Property System.CharEnumerator.Current As System.Char (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'z As String') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Next (Regular) Block[B4] Entering: {R5} .locals {R5} { CaptureIds: [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.String) (Syntax: 'z') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z') Leaving: {R5} {R4} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'z?.ToString()') Expression: IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z') Arguments(0) Next (Regular) Block[B2] Leaving: {R5} {R4} } } } .finally {R6} { Block[B6] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B9] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_03() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer(,), result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_04() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Enumerable, result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class Public Structure Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Structure Public Structure Enumerator Public ReadOnly Property Current As Integer Get Return 1 End Get End Property Public Function MoveNext() As Boolean Return False End Function End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_05() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Enumerable, result As Integer) 'BIND:"Sub M" For Each z As Integer in x result = z Next End Sub End Class Public Structure Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Structure Public Structure Enumerator Implements System.IDisposable Public ReadOnly Property Current As Integer Get Return 1 End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Function MoveNext() As Boolean Return False End Function End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Integer') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer') Right: IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } Block[B5] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_06() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As System.Collections.Generic.IEnumerable(Of Integer), result As Integer) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32)) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { Block[B4] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_11() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Object, result As Object) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { CaptureIds: [1] Block[B4] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_12() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C, result As Integer) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC32023: Expression is of type 'C', which is not a collection type. For Each z in x ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(0) Next (Regular) Block[B3] Entering: {R1} .locals {R1} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(1): IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_15() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M() 'BIND:"Sub M" For Each If(GetC(), Me).F in Me Next End Sub Public F As C Public ReadOnly Property Current As C Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class Module Ext <Runtime.CompilerServices.Extension> Public Function GetEnumerator(this As C) As C Return this End Function End Module ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B6] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()') Value: IInvocationOperation (Function C.GetC() As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetC()') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()') Leaving: {R3} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()') Next (Regular) Block[B6] Leaving: {R3} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F') Left: IFieldReferenceOperation: C.F As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(GetC(), Me).F') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me)') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Next (Regular) Block[B2] Leaving: {R2} } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_16() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As System.Collections.IEnumerable, result As Object) 'BIND:"Sub M" For Each z in x result = z Next End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B7] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Finalizing: {R5} Leaving: {R3} {R2} {R1} Next (Regular) Block[B3] Entering: {R4} .locals {R4} { Locals: [z As System.Object] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R4} } } .finally {R5} { CaptureIds: [1] Block[B4] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x') Arguments(0) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B7] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_17() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer(), result As Long) 'BIND:"Sub M" For Each z As Long in x result = z Next End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingValue) Operand: IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Right: ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z') Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_18() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Boolean) 'BIND:"Sub M" For Each x in Me If x Continue For End If result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] [B4] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B4] ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B5] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_19() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Boolean) 'BIND:"Sub M" For Each x in Me If x Exit For End If result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B4] ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R2} {R1} Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_20() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M" For Each x in Me While y result = y Continue For End While result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] [B5] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_21() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M" For Each x in Me While y result = y Exit For End While result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Boolean Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [x As System.Boolean] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B6] Leaving: {R2} {R1} Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R2} } } Block[B6] - Exit Predecessors: [B2] [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_22() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" For Each z As Long in If(GetC(), GetC()) Next End Sub Shared Function GetC() As C Return Nothing End Function Shared Function GetEnumerator() As C Return Nothing End Function Shared Function MoveNext() As Boolean Return Nothing End Function Shared ReadOnly Property Current As Integer Get Return 1 End Get End Property End Class]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. For Each z As Long in If(GetC(), GetC()) ~~~~~~~~~~~~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(GetC(), GetC())') Value: IInvocationOperation (Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'If(GetC(), GetC())') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation (Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(GetC(), GetC())') Instance Receiver: null Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int64] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNumeric) Operand: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long') Instance Receiver: null Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_23() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As C) 'BIND:"Sub M" For Each z in x Next End Sub Function GetEnumerator(<System.Runtime.CompilerServices.CallerMemberName> Optional member As String = "") As C Return Nothing End Function Function MoveNext(Optional s As String = "ABC") As Boolean Return Nothing End Function ReadOnly Property Current(Optional d As Double = 123.45) As Integer Get Return 1 End Get End Property End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function C.GetEnumerator([member As System.String = ""]) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: member) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "M", IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext([s As System.String = "ABC"]) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "ABC", IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R1} Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [z As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z') Left: ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Right: IPropertyReferenceOperation: ReadOnly Property C.Current([d As System.Double = 123.45]) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: d) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 123.45, IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R2} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, useLatestFramework:=True) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_24() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as Integer) 'BIND:"Sub M" For Each x As Integer in GetC(x) result = x Next End Sub Public Function GetC(ByRef x as Integer) As C Return Me End Function Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As Integer Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { Locals: [x As System.Int32] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC(x)') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'GetC(x)') Instance Receiver: IInvocationOperation ( Function C.GetC(ByRef x As System.Int32) As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC(x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'GetC') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Arguments(0) Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'GetC(x)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { Locals: [x As System.Int32] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As Integer') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R3} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub ForEachFlow_25() Dim source = <![CDATA[ Imports System Public NotInheritable Class C Sub M(result as C) 'BIND:"Sub M" For Each x As C in x result = x Next End Sub Public Function GetEnumerator() As C Return Me End Function Public ReadOnly Property Current As C Get Return Nothing End Get End Property Public Function MoveNext() As Boolean Return False End Function Public Shared Function GetC() As C Return Nothing End Function End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. For Each x As C in x ~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { Locals: [x As C] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x') Arguments(0) Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] [B3] Statements (0) Jump if False (Regular) to Block[B4] IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Arguments(0) Leaving: {R1} Next (Regular) Block[B3] Entering: {R3} .locals {R3} { Locals: [x As C] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As C') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'x As C') Right: IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'x As C') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x') Next (Regular) Block[B2] Leaving: {R3} } } Block[B4] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./docs/compilers/Dynamic Analysis/MetadataFormat.md
# Dynamic Analysis Metadata Format Specification (v 0.2) ### Overview The format is based on concepts defined in the ECMA-335 Partition II metadata standard and in [Portable PDB format](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md). ## Metadata Layout The physical layout of the Dynamic Analysis metadata blob starts with [Header](#Header), followed by [Tables](#Tables), followed by [Heaps](#Heaps). Layout of each of these three parts is defined in the following sections. When stored in a managed PE file, the Dynamic Analysis metadata blob is embedded as a Manifest Resource (see ECMA-335 §6.2.2 and §22.24) of name ```<DynamicAnalysisData>```. Unless stated otherwise, all binary values are stored in little-endian format. This document uses the term _(un)signed compressed integer_ for an encoding of an (un)signed 29-bit integer as defined in ECMA §23.2. ## Header | Offset | Size | Field | Description | |:--------|:-----|:---------------|----------------------------------------------------------------| | 0 | 4 | Signature | 0x44 0x41 0x4D 0x44 (ASCII string: "DAMD") | | 4 | 1 | MajorVersion | Major version of the format (0) | | 5 | 1 | MinorVersion | Minor version of the format (2) | | 6 | 4*T | TableRowCounts | Row count (encoded as uint32) of each table in the metadata | | 6 + T*4 | 4*H | HeapSizes | Size (encoded as uint32) of each heap in bytes | The number of tables in this version of the format is T = 2. These tables are Document Table and Method Table and their sizes are stored in this order. No table may contain more than 0x1000000 rows. The number of heaps in this version of the format is H = 2. These heaps are GUID Heap and Blob Heap and their sizes are stored in this order. No heap may be larger than 2^19 bytes (0.5 GB). ## <a name="Tables"></a>Tables Entities stored in tables are referred to by _row id_ if used in a context that implies the table. The first row of the table has row id 1. If the table is not implied by the context the entity is referred to by its _token_ -- a 32-bit unsigned integer that combines the id of the table (in highest 8 bits) and the row id of the entity within that table (in lowest 24 bits). ### <a name="DocumentTable"></a>Document Table: 0x01 The Document table has the following columns: * _Name_ (Blob heap index of [document name blob](#DocumentNameBlob)) * _HashAlgorithm_ (Guid heap index) * _Hash_ (Blob heap index) ### <a name="MethodTable"></a>Method Table: 0x02 The Method table has the following columns: * _Spans_ (Blob heap index of [span blob](#SpanBlob)) ## <a name="Heaps"></a>Heaps ### GUID The encoding of GUID heap is the same as the encoding of ECMA #GUID heap defined in ECMA-335 §24.2.5. Values stored in GUID heap are referred to by its _index_. The first value stored in the heap has index 1, the second value stored in the heap has index 2, etc. ### Blob The encoding of Blob heap is the same as the encoding of ECMA #Blob heap defined in ECMA-335 §24.2.4. Values stored in Blob heap are referred to by its _offset_ in the heap (the distance between the start of the heap and the first byte ot the encoded value). The first value of the heap has offset 0, size 1B, and encoded value 0x00 (it represents an empty blob). ### <a name="SpansBlob"></a>Spans Blob _Span_ is a quadruple of integers and a document reference: * Start Line * Start Column * End Line * End Column * Document The values of must satisfy the following constraints * Start Line is within range [0, 0x20000000) * End Line is within range [0, 0x20000000) * Start Column is within range [0, 0x10000) * End Column is within range [0, 0x10000) * End Line is greater or equal to Start Line. * If Start Line is equal to End Line then End Column is greater than Start Column. _Spans blob_ has the following structure: Blob ::= header span-record (span-record | document-record)* #### header | component | value stored | integer representation | |:-------------------|:------------------------------|:-----------------------| | _InitialDocument_ | Document row id | unsigned compressed | #### span-record | component | value stored | integer representation | |:---------------|:--------------------------------------------------------|:--------------------------------------------| | _ΔLines_ | _EndLine_ - _StartLine_ | unsigned compressed | | _ΔColumns_ | _EndColumn_ - _StartColumn_ | _ΔLines_ = 0: unsigned compressed, non-zero | | | | _ΔLines_ > 0: signed compressed | | _δStartLine_ | _StartLine_ if this is the first _span-record_ | unsigned compressed | | | _StartLine_ - _PreviousSpan_._StartLine_ otherwise | signed compressed | | _δStartColumn_ | _StartColumn_ if this is the first _span-record_ | unsigned compressed | | | _StartColumn_ - _PreviousSpan_._StartColumn_ otherwise | signed compressed | Where _PreviousSpan_ is the span encoded in the previous _span-record_. #### document-record | component | value stored | integer representation | |:-------------|:-----------------------------------|:-------------------------------| | _ΔLines_ | 0 | unsigned compressed | | _ΔColumns_ | 0 | unsigned compressed | | _Document_ | Document row id | unsigned compressed | Each _span-record_ represents a single _Span_. When decoding the blob the _Document_ property of a _Span_ is determined by the closest preceding _document-record_ and by _InitialDocument_ if there is no preceding _document-record_. The values of _Start Line_, _Start Column_, _End Line_ and _End Column_ of a Span are calculated based upon the values of the previous Span (if any) and the data stored in the record. - - - **Note** This encoding is similar to encoding of [sequence points blob](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#SequencePointsBlob) in Portable PDB format. - - - ### <a name="DocumentNameBlob"></a>Document Name Blob _Document name blob_ is a sequence: Blob ::= separator part+ where * _separator_ is a UTF8 encoded character, or byte 0 to represent an empty separator. * _part_ is a compressed integer into the Blob heap, where the part is stored in UTF8 encoding (0 represents an empty string). The document name is a concatenation of the _parts_ separated by the _separator_. - - - **Note** This encoding is the same as the encoding of [document name blob](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#DocumentNameBlob) in Portable PDB format. - - -
# Dynamic Analysis Metadata Format Specification (v 0.2) ### Overview The format is based on concepts defined in the ECMA-335 Partition II metadata standard and in [Portable PDB format](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md). ## Metadata Layout The physical layout of the Dynamic Analysis metadata blob starts with [Header](#Header), followed by [Tables](#Tables), followed by [Heaps](#Heaps). Layout of each of these three parts is defined in the following sections. When stored in a managed PE file, the Dynamic Analysis metadata blob is embedded as a Manifest Resource (see ECMA-335 §6.2.2 and §22.24) of name ```<DynamicAnalysisData>```. Unless stated otherwise, all binary values are stored in little-endian format. This document uses the term _(un)signed compressed integer_ for an encoding of an (un)signed 29-bit integer as defined in ECMA §23.2. ## Header | Offset | Size | Field | Description | |:--------|:-----|:---------------|----------------------------------------------------------------| | 0 | 4 | Signature | 0x44 0x41 0x4D 0x44 (ASCII string: "DAMD") | | 4 | 1 | MajorVersion | Major version of the format (0) | | 5 | 1 | MinorVersion | Minor version of the format (2) | | 6 | 4*T | TableRowCounts | Row count (encoded as uint32) of each table in the metadata | | 6 + T*4 | 4*H | HeapSizes | Size (encoded as uint32) of each heap in bytes | The number of tables in this version of the format is T = 2. These tables are Document Table and Method Table and their sizes are stored in this order. No table may contain more than 0x1000000 rows. The number of heaps in this version of the format is H = 2. These heaps are GUID Heap and Blob Heap and their sizes are stored in this order. No heap may be larger than 2^19 bytes (0.5 GB). ## <a name="Tables"></a>Tables Entities stored in tables are referred to by _row id_ if used in a context that implies the table. The first row of the table has row id 1. If the table is not implied by the context the entity is referred to by its _token_ -- a 32-bit unsigned integer that combines the id of the table (in highest 8 bits) and the row id of the entity within that table (in lowest 24 bits). ### <a name="DocumentTable"></a>Document Table: 0x01 The Document table has the following columns: * _Name_ (Blob heap index of [document name blob](#DocumentNameBlob)) * _HashAlgorithm_ (Guid heap index) * _Hash_ (Blob heap index) ### <a name="MethodTable"></a>Method Table: 0x02 The Method table has the following columns: * _Spans_ (Blob heap index of [span blob](#SpanBlob)) ## <a name="Heaps"></a>Heaps ### GUID The encoding of GUID heap is the same as the encoding of ECMA #GUID heap defined in ECMA-335 §24.2.5. Values stored in GUID heap are referred to by its _index_. The first value stored in the heap has index 1, the second value stored in the heap has index 2, etc. ### Blob The encoding of Blob heap is the same as the encoding of ECMA #Blob heap defined in ECMA-335 §24.2.4. Values stored in Blob heap are referred to by its _offset_ in the heap (the distance between the start of the heap and the first byte ot the encoded value). The first value of the heap has offset 0, size 1B, and encoded value 0x00 (it represents an empty blob). ### <a name="SpansBlob"></a>Spans Blob _Span_ is a quadruple of integers and a document reference: * Start Line * Start Column * End Line * End Column * Document The values of must satisfy the following constraints * Start Line is within range [0, 0x20000000) * End Line is within range [0, 0x20000000) * Start Column is within range [0, 0x10000) * End Column is within range [0, 0x10000) * End Line is greater or equal to Start Line. * If Start Line is equal to End Line then End Column is greater than Start Column. _Spans blob_ has the following structure: Blob ::= header span-record (span-record | document-record)* #### header | component | value stored | integer representation | |:-------------------|:------------------------------|:-----------------------| | _InitialDocument_ | Document row id | unsigned compressed | #### span-record | component | value stored | integer representation | |:---------------|:--------------------------------------------------------|:--------------------------------------------| | _ΔLines_ | _EndLine_ - _StartLine_ | unsigned compressed | | _ΔColumns_ | _EndColumn_ - _StartColumn_ | _ΔLines_ = 0: unsigned compressed, non-zero | | | | _ΔLines_ > 0: signed compressed | | _δStartLine_ | _StartLine_ if this is the first _span-record_ | unsigned compressed | | | _StartLine_ - _PreviousSpan_._StartLine_ otherwise | signed compressed | | _δStartColumn_ | _StartColumn_ if this is the first _span-record_ | unsigned compressed | | | _StartColumn_ - _PreviousSpan_._StartColumn_ otherwise | signed compressed | Where _PreviousSpan_ is the span encoded in the previous _span-record_. #### document-record | component | value stored | integer representation | |:-------------|:-----------------------------------|:-------------------------------| | _ΔLines_ | 0 | unsigned compressed | | _ΔColumns_ | 0 | unsigned compressed | | _Document_ | Document row id | unsigned compressed | Each _span-record_ represents a single _Span_. When decoding the blob the _Document_ property of a _Span_ is determined by the closest preceding _document-record_ and by _InitialDocument_ if there is no preceding _document-record_. The values of _Start Line_, _Start Column_, _End Line_ and _End Column_ of a Span are calculated based upon the values of the previous Span (if any) and the data stored in the record. - - - **Note** This encoding is similar to encoding of [sequence points blob](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#SequencePointsBlob) in Portable PDB format. - - - ### <a name="DocumentNameBlob"></a>Document Name Blob _Document name blob_ is a sequence: Blob ::= separator part+ where * _separator_ is a UTF8 encoded character, or byte 0 to represent an empty separator. * _part_ is a compressed integer into the Blob heap, where the part is stored in UTF8 encoding (0 represents an empty string). The document name is a concatenation of the _parts_ separated by the _separator_. - - - **Note** This encoding is the same as the encoding of [document name blob](https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#DocumentNameBlob) in Portable PDB format. - - -
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/FrameDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// This class provides method name, argument and return type information for the Call Stack window and DTE. /// </summary> /// <remarks> /// While it might be nice to provide language-specific syntax in the Call Stack window, previous implementations have /// always used C# syntax (but with language-specific "special names"). Since these names are exposed through public /// APIs, we will remain consistent with the old behavior (for consumers who may be parsing the frame names). /// </remarks> internal abstract class FrameDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> : IDkmLanguageFrameDecoder where TCompilation : Compilation where TMethodSymbol : class, IMethodSymbolInternal where TModuleSymbol : class, IModuleSymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TTypeParameterSymbol : class, ITypeParameterSymbolInternal { private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder; internal FrameDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder) { _instructionDecoder = instructionDecoder; } void IDkmLanguageFrameDecoder.GetFrameName( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine) { try { Debug.Assert((argumentFlags & (DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Values)) == argumentFlags, $"Unexpected argumentFlags '{argumentFlags}'"); GetNameWithGenericTypeArguments(workList, frame, onSuccess: method => GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine, method), onFailure: e => completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e))); } catch (NotImplementedMetadataException) { inspectionContext.GetFrameName(workList, frame, argumentFlags, completionRoutine); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmLanguageFrameDecoder.GetFrameReturnType( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine) { try { GetNameWithGenericTypeArguments(workList, frame, onSuccess: method => completionRoutine(new DkmGetFrameReturnTypeAsyncResult(_instructionDecoder.GetReturnTypeName(method))), onFailure: e => completionRoutine(DkmGetFrameReturnTypeAsyncResult.CreateErrorResult(e))); } catch (NotImplementedMetadataException) { inspectionContext.GetFrameReturnType(workList, frame, completionRoutine); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private void GetNameWithGenericTypeArguments( DkmWorkList workList, DkmStackWalkFrame frame, Action<TMethodSymbol> onSuccess, Action<Exception> onFailure) { // NOTE: We could always call GetClrGenericParameters, pass them to GetMethod and have that // return a constructed method symbol, but it seems unwise to call GetClrGenericParameters // for all frames (as this call requires a round-trip to the debuggee process). var instructionAddress = (DkmClrInstructionAddress)frame.InstructionAddress; var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance); var method = _instructionDecoder.GetMethod(compilation, instructionAddress); var typeParameters = _instructionDecoder.GetAllTypeParameters(method); if (!typeParameters.IsEmpty) { frame.GetClrGenericParameters( workList, result => { try { // DkmGetClrGenericParametersAsyncResult.ParameterTypeNames will throw if ErrorCode != 0. var serializedTypeNames = (result.ErrorCode == 0) ? result.ParameterTypeNames : null; var typeArguments = _instructionDecoder.GetTypeSymbols(compilation, method, serializedTypeNames); if (!typeArguments.IsEmpty) { method = _instructionDecoder.ConstructMethod(method, typeParameters, typeArguments); } onSuccess(method); } catch (Exception e) { onFailure(e); } }); } else { onSuccess(method); } } private void GetFrameName( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine, TMethodSymbol method) { var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types); var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names); if (argumentFlags.Includes(DkmVariableInfoFlags.Values)) { // No need to compute the Expandable bit on // argument values since that can be expensive. inspectionContext = DkmInspectionContext.Create( inspectionContext.InspectionSession, inspectionContext.RuntimeInstance, inspectionContext.Thread, inspectionContext.Timeout, inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoExpansion, inspectionContext.FuncEvalFlags, inspectionContext.Radix, inspectionContext.Language, inspectionContext.ReturnValue, inspectionContext.AdditionalVisualizationData, inspectionContext.AdditionalVisualizationDataPriority, inspectionContext.ReturnValues); // GetFrameArguments returns an array of formatted argument values. We'll pass // ourselves (GetFrameName) as the continuation of the GetFrameArguments call. inspectionContext.GetFrameArguments( workList, frame, result => { // DkmGetFrameArgumentsAsyncResult.Arguments will throw if ErrorCode != 0. var argumentValues = (result.ErrorCode == 0) ? result.Arguments : null; try { ArrayBuilder<string?>? builder = null; if (argumentValues != null) { builder = ArrayBuilder<string?>.GetInstance(); foreach (var argument in argumentValues) { var formattedArgument = argument as DkmSuccessEvaluationResult; // Not expecting Expandable bit, at least not from this EE. Debug.Assert((formattedArgument == null) || (formattedArgument.Flags & DkmEvaluationResultFlags.Expandable) == 0); builder.Add(formattedArgument?.Value); } } var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: builder); builder?.Free(); completionRoutine(new DkmGetFrameNameAsyncResult(frameName)); } catch (Exception e) { completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e)); } finally { if (argumentValues != null) { foreach (var argument in argumentValues) { argument.Close(); } } } }); } else { var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: null); completionRoutine(new DkmGetFrameNameAsyncResult(frameName)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// This class provides method name, argument and return type information for the Call Stack window and DTE. /// </summary> /// <remarks> /// While it might be nice to provide language-specific syntax in the Call Stack window, previous implementations have /// always used C# syntax (but with language-specific "special names"). Since these names are exposed through public /// APIs, we will remain consistent with the old behavior (for consumers who may be parsing the frame names). /// </remarks> internal abstract class FrameDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> : IDkmLanguageFrameDecoder where TCompilation : Compilation where TMethodSymbol : class, IMethodSymbolInternal where TModuleSymbol : class, IModuleSymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TTypeParameterSymbol : class, ITypeParameterSymbolInternal { private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder; internal FrameDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder) { _instructionDecoder = instructionDecoder; } void IDkmLanguageFrameDecoder.GetFrameName( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine) { try { Debug.Assert((argumentFlags & (DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Values)) == argumentFlags, $"Unexpected argumentFlags '{argumentFlags}'"); GetNameWithGenericTypeArguments(workList, frame, onSuccess: method => GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine, method), onFailure: e => completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e))); } catch (NotImplementedMetadataException) { inspectionContext.GetFrameName(workList, frame, argumentFlags, completionRoutine); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmLanguageFrameDecoder.GetFrameReturnType( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine) { try { GetNameWithGenericTypeArguments(workList, frame, onSuccess: method => completionRoutine(new DkmGetFrameReturnTypeAsyncResult(_instructionDecoder.GetReturnTypeName(method))), onFailure: e => completionRoutine(DkmGetFrameReturnTypeAsyncResult.CreateErrorResult(e))); } catch (NotImplementedMetadataException) { inspectionContext.GetFrameReturnType(workList, frame, completionRoutine); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private void GetNameWithGenericTypeArguments( DkmWorkList workList, DkmStackWalkFrame frame, Action<TMethodSymbol> onSuccess, Action<Exception> onFailure) { // NOTE: We could always call GetClrGenericParameters, pass them to GetMethod and have that // return a constructed method symbol, but it seems unwise to call GetClrGenericParameters // for all frames (as this call requires a round-trip to the debuggee process). var instructionAddress = (DkmClrInstructionAddress)frame.InstructionAddress; var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance); var method = _instructionDecoder.GetMethod(compilation, instructionAddress); var typeParameters = _instructionDecoder.GetAllTypeParameters(method); if (!typeParameters.IsEmpty) { frame.GetClrGenericParameters( workList, result => { try { // DkmGetClrGenericParametersAsyncResult.ParameterTypeNames will throw if ErrorCode != 0. var serializedTypeNames = (result.ErrorCode == 0) ? result.ParameterTypeNames : null; var typeArguments = _instructionDecoder.GetTypeSymbols(compilation, method, serializedTypeNames); if (!typeArguments.IsEmpty) { method = _instructionDecoder.ConstructMethod(method, typeParameters, typeArguments); } onSuccess(method); } catch (Exception e) { onFailure(e); } }); } else { onSuccess(method); } } private void GetFrameName( DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine, TMethodSymbol method) { var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types); var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names); if (argumentFlags.Includes(DkmVariableInfoFlags.Values)) { // No need to compute the Expandable bit on // argument values since that can be expensive. inspectionContext = DkmInspectionContext.Create( inspectionContext.InspectionSession, inspectionContext.RuntimeInstance, inspectionContext.Thread, inspectionContext.Timeout, inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoExpansion, inspectionContext.FuncEvalFlags, inspectionContext.Radix, inspectionContext.Language, inspectionContext.ReturnValue, inspectionContext.AdditionalVisualizationData, inspectionContext.AdditionalVisualizationDataPriority, inspectionContext.ReturnValues); // GetFrameArguments returns an array of formatted argument values. We'll pass // ourselves (GetFrameName) as the continuation of the GetFrameArguments call. inspectionContext.GetFrameArguments( workList, frame, result => { // DkmGetFrameArgumentsAsyncResult.Arguments will throw if ErrorCode != 0. var argumentValues = (result.ErrorCode == 0) ? result.Arguments : null; try { ArrayBuilder<string?>? builder = null; if (argumentValues != null) { builder = ArrayBuilder<string?>.GetInstance(); foreach (var argument in argumentValues) { var formattedArgument = argument as DkmSuccessEvaluationResult; // Not expecting Expandable bit, at least not from this EE. Debug.Assert((formattedArgument == null) || (formattedArgument.Flags & DkmEvaluationResultFlags.Expandable) == 0); builder.Add(formattedArgument?.Value); } } var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: builder); builder?.Free(); completionRoutine(new DkmGetFrameNameAsyncResult(frameName)); } catch (Exception e) { completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e)); } finally { if (argumentValues != null) { foreach (var argument in argumentValues) { argument.Close(); } } } }); } else { var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: null); completionRoutine(new DkmGetFrameNameAsyncResult(frameName)); } } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/AsyncSymbolVisitor`1.cs
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class AsyncSymbolVisitor<TResult> : SymbolVisitor<ValueTask<TResult>> { protected abstract TResult DefaultResult { get; } public override ValueTask<TResult> Visit(ISymbol? symbol) => symbol?.Accept(this) ?? ValueTaskFactory.FromResult(DefaultResult); public override ValueTask<TResult> DefaultVisit(ISymbol symbol) => ValueTaskFactory.FromResult(DefaultResult); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class AsyncSymbolVisitor<TResult> : SymbolVisitor<ValueTask<TResult>> { protected abstract TResult DefaultResult { get; } public override ValueTask<TResult> Visit(ISymbol? symbol) => symbol?.Accept(this) ?? ValueTaskFactory.FromResult(DefaultResult); public override ValueTask<TResult> DefaultVisit(ISymbol symbol) => ValueTaskFactory.FromResult(DefaultResult); } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Compilers/CSharp/Portable/Symbols/MetadataOrSourceAssemblySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents source or metadata assembly. /// </summary> internal abstract class MetadataOrSourceAssemblySymbol : NonMissingAssemblySymbol { /// <summary> /// An array of cached Cor types defined in this assembly. /// Lazily filled by GetDeclaredSpecialType method. /// </summary> private NamedTypeSymbol[] _lazySpecialTypes; /// <summary> /// How many Cor types have we cached so far. /// </summary> private int _cachedSpecialTypes; private NativeIntegerTypeSymbol[] _lazyNativeIntegerTypes; /// <summary> /// Lookup declaration for predefined CorLib type in this Assembly. /// </summary> /// <param name="type"></param> /// <returns></returns> internal sealed override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true); ModuleSymbol module = this.Modules[0]; NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName); if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public) { result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type); } RegisterDeclaredSpecialType(result); } return _lazySpecialTypes[(int)type]; } /// <summary> /// Register declaration of predefined CorLib type in this Assembly. /// </summary> /// <param name="corType"></param> internal sealed override void RegisterDeclaredSpecialType(NamedTypeSymbol corType) { SpecialType typeId = corType.SpecialType; Debug.Assert(typeId != SpecialType.None); Debug.Assert(ReferenceEquals(corType.ContainingAssembly, this)); Debug.Assert(corType.ContainingModule.Ordinal == 0); Debug.Assert(ReferenceEquals(this.CorLibrary, this)); if (_lazySpecialTypes == null) { Interlocked.CompareExchange(ref _lazySpecialTypes, new NamedTypeSymbol[(int)SpecialType.Count + 1], null); } if ((object)Interlocked.CompareExchange(ref _lazySpecialTypes[(int)typeId], corType, null) != null) { Debug.Assert(ReferenceEquals(corType, _lazySpecialTypes[(int)typeId]) || (corType.Kind == SymbolKind.ErrorType && _lazySpecialTypes[(int)typeId].Kind == SymbolKind.ErrorType)); } else { Interlocked.Increment(ref _cachedSpecialTypes); Debug.Assert(_cachedSpecialTypes > 0 && _cachedSpecialTypes <= (int)SpecialType.Count); } } /// <summary> /// Continue looking for declaration of predefined CorLib type in this Assembly /// while symbols for new type declarations are constructed. /// </summary> internal override bool KeepLookingForDeclaredSpecialTypes { get { return ReferenceEquals(this.CorLibrary, this) && _cachedSpecialTypes < (int)SpecialType.Count; } } private ICollection<string> _lazyTypeNames; private ICollection<string> _lazyNamespaceNames; public override ICollection<string> TypeNames { get { if (_lazyTypeNames == null) { Interlocked.CompareExchange(ref _lazyTypeNames, UnionCollection<string>.Create(this.Modules, m => m.TypeNames), null); } return _lazyTypeNames; } } internal sealed override NamedTypeSymbol GetNativeIntegerType(NamedTypeSymbol underlyingType) { if (_lazyNativeIntegerTypes == null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes, new NativeIntegerTypeSymbol[2], null); } int index = underlyingType.SpecialType switch { SpecialType.System_IntPtr => 0, SpecialType.System_UIntPtr => 1, _ => throw ExceptionUtilities.UnexpectedValue(underlyingType.SpecialType), }; if (_lazyNativeIntegerTypes[index] is null) { Interlocked.CompareExchange(ref _lazyNativeIntegerTypes[index], new NativeIntegerTypeSymbol(underlyingType), null); } return _lazyNativeIntegerTypes[index]; } public override ICollection<string> NamespaceNames { get { if (_lazyNamespaceNames == null) { Interlocked.CompareExchange(ref _lazyNamespaceNames, UnionCollection<string>.Create(this.Modules, m => m.NamespaceNames), null); } return _lazyNamespaceNames; } } /// <summary> /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol[] _lazySpecialTypeMembers; /// <summary> /// Lookup member declaration in predefined CorLib type in this Assembly. Only valid if this /// assembly is the Cor Library /// </summary> internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member) { #if DEBUG foreach (var module in this.Modules) { Debug.Assert(module.GetReferencedAssemblies().Length == 0); } #endif if (_lazySpecialTypeMembers == null || ReferenceEquals(_lazySpecialTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazySpecialTypeMembers == null) { var specialTypeMembers = new Symbol[(int)SpecialMember.Count]; for (int i = 0; i < specialTypeMembers.Length; i++) { specialTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazySpecialTypeMembers, specialTypeMembers, null); } var descriptor = SpecialMembers.GetDescriptor(member); NamedTypeSymbol type = GetDeclaredSpecialType((SpecialType)descriptor.DeclaringTypeId); Symbol result = null; if (!type.IsErrorType()) { result = CSharpCompilation.GetRuntimeMember(type, descriptor, CSharpCompilation.SpecialMembersSignatureComparer.Instance, accessWithinOpt: null); } Interlocked.CompareExchange(ref _lazySpecialTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazySpecialTypeMembers[(int)member]; } /// <summary> /// Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. /// Assumes that the public key has been determined. The result will be cached. /// </summary> /// <param name="potentialGiverOfAccess"></param> /// <returns></returns> /// <remarks></remarks> protected IVTConclusion MakeFinalIVTDetermination(AssemblySymbol potentialGiverOfAccess) { IVTConclusion result; if (AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, out result)) return result; result = IVTConclusion.NoRelationshipClaimed; // returns an empty list if there was no IVT attribute at all for the given name // A name w/o a key is represented by a list with an entry that is empty IEnumerable<ImmutableArray<byte>> publicKeys = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name); // We have an easy out here. Suppose the assembly wanting access is // being compiled as a module. You can only strong-name an assembly. So we are going to optimistically // assume that it is going to be compiled into an assembly with a matching strong name, if necessary. if (publicKeys.Any() && this.IsNetModule()) { return IVTConclusion.Match; } // look for one that works, if none work, then return the failure for the last one examined. foreach (var key in publicKeys) { // We pass the public key of this assembly explicitly so PerformIVTCheck does not need // to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(this.PublicKey, key); Debug.Assert(result != IVTConclusion.NoRelationshipClaimed); if (result == IVTConclusion.Match || result == IVTConclusion.OneSignedOneNot) { break; } } AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result); return result; } //EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant //internals access to us to the conclusion reached. private ConcurrentDictionary<AssemblySymbol, IVTConclusion> _assembliesToWhichInternalAccessHasBeenAnalyzed; private ConcurrentDictionary<AssemblySymbol, IVTConclusion> AssembliesToWhichInternalAccessHasBeenDetermined { get { if (_assembliesToWhichInternalAccessHasBeenAnalyzed == null) Interlocked.CompareExchange(ref _assembliesToWhichInternalAccessHasBeenAnalyzed, new ConcurrentDictionary<AssemblySymbol, IVTConclusion>(), null); return _assembliesToWhichInternalAccessHasBeenAnalyzed; } } internal virtual bool IsNetModule() => false; } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicParenthesesReducer.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 VisualBasicParenthesesReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub 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 VisualBasicParenthesesReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub 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
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/VisualStudio/Core/Def/SymbolSearch/VisualStudioSymbolSearchService.LogService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.SymbolSearch { internal partial class VisualStudioSymbolSearchService { private class LogService : ForegroundThreadAffinitizedObject, ISymbolSearchLogService { private static readonly LinkedList<string> s_log = new(); private readonly IVsActivityLog _activityLog; public LogService(IThreadingContext threadingContext, IVsActivityLog activityLog) : base(threadingContext) { _activityLog = activityLog; } public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => LogAsync(text, __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => LogAsync(text + ". " + exception, __ACTIVITYLOG_ENTRYTYPE.ALE_ERROR); private ValueTask LogAsync(string text, __ACTIVITYLOG_ENTRYTYPE type) { Log(text, type); return default; } private void Log(string text, __ACTIVITYLOG_ENTRYTYPE type) { if (!IsForeground()) { InvokeBelowInputPriorityAsync(() => Log(text, type)); return; } AssertIsForeground(); _activityLog?.LogEntry((uint)type, SymbolSearchUpdateEngine.HostId, text); // Keep a running in memory log as well for debugging purposes. s_log.AddLast(text); while (s_log.Count > 100) { s_log.RemoveFirst(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.SymbolSearch { internal partial class VisualStudioSymbolSearchService { private class LogService : ForegroundThreadAffinitizedObject, ISymbolSearchLogService { private static readonly LinkedList<string> s_log = new(); private readonly IVsActivityLog _activityLog; public LogService(IThreadingContext threadingContext, IVsActivityLog activityLog) : base(threadingContext) { _activityLog = activityLog; } public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => LogAsync(text, __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => LogAsync(text + ". " + exception, __ACTIVITYLOG_ENTRYTYPE.ALE_ERROR); private ValueTask LogAsync(string text, __ACTIVITYLOG_ENTRYTYPE type) { Log(text, type); return default; } private void Log(string text, __ACTIVITYLOG_ENTRYTYPE type) { if (!IsForeground()) { InvokeBelowInputPriorityAsync(() => Log(text, type)); return; } AssertIsForeground(); _activityLog?.LogEntry((uint)type, SymbolSearchUpdateEngine.HostId, text); // Keep a running in memory log as well for debugging purposes. s_log.AddLast(text); while (s_log.Count > 100) { s_log.RemoveFirst(); } } } } }
-1
dotnet/roslyn
55,724
Region analysis of nameof
Fixes https://github.com/dotnet/roslyn/issues/53591
jcouv
2021-08-19T16:17:11Z
2021-08-21T02:45:07Z
29ba4f82628f9a1583f1b56c1cbf0318e4de1e63
5e54d3cb1f087d5d9abab8dfe8016fd381fc993c
Region analysis of nameof. Fixes https://github.com/dotnet/roslyn/issues/53591
./src/VisualStudio/CSharp/Test/CodeModel/FileCodeImportTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeImportTests : AbstractFileCodeElementTests { public FileCodeImportTests() : base(@"using System; using Goo = System.Data;") { } private CodeImport GetCodeImport(object path) { return (CodeImport)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Name() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.Name; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void FullName() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.FullName; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Kind() { var import = GetCodeImport(1); Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Namespace() { var import = GetCodeImport(1); Assert.Equal("System", import.Namespace); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Alias() { var import = GetCodeImport(2); Assert.Equal("Goo", import.Alias); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, startPoint.Line); Assert.Equal(13, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, endPoint.Line); Assert.Equal(24, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var import = GetCodeImport(2); var startPoint = import.StartPoint; Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var import = GetCodeImport(2); var endPoint = import.EndPoint; Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeImportTests : AbstractFileCodeElementTests { public FileCodeImportTests() : base(@"using System; using Goo = System.Data;") { } private CodeImport GetCodeImport(object path) { return (CodeImport)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Name() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.Name; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void FullName() { var import = GetCodeImport(1); Assert.Throws<COMException>(() => { var value = import.FullName; }); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Kind() { var import = GetCodeImport(1); Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Namespace() { var import = GetCodeImport(1); Assert.Equal("System", import.Namespace); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Alias() { var import = GetCodeImport(2); Assert.Equal("Goo", import.Alias); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, startPoint.Line); Assert.Equal(13, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var import = GetCodeImport(2); var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var import = GetCodeImport(2); Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(2, endPoint.Line); Assert.Equal(24, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var import = GetCodeImport(2); Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var import = GetCodeImport(2); var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var import = GetCodeImport(2); var startPoint = import.StartPoint; Assert.Equal(2, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var import = GetCodeImport(2); var endPoint = import.EndPoint; Assert.Equal(2, endPoint.Line); Assert.Equal(25, endPoint.LineCharOffset); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] [WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N1.N2 { class D { public static void F() { } } } class C { static void Main() => N1.N2.D.F(); }"; var source2 = @" namespace N1.N2 { class D { public static void F() { } } namespace M1.M2 { class E { public static void G() { } } } } class C { static void Main() => N1.N2.M1.M2.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.M1.M2.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] [WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N1.N2 { class D { public static void F() { } } } class C { static void Main() => N1.N2.D.F(); }"; var source2 = @" namespace N1.N2 { class D { public static void F() { } } namespace M1.M2 { class E { public static void G() { } } } } class C { static void Main() => N1.N2.M1.M2.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.M1.M2.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } [Fact] public void Struct_ImplementSynthesizedConstructor() { var source0 = @" struct S { int a = 1; int b; } "; var source1 = @" struct S { int a = 1; int b; public S() { b = 2; } } "; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var ctor0 = compilation0.GetMember<MethodSymbol>("S..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("S..ctor"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "S"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: ret }"); } } }
1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructor_DeleteParameterless() { var src1 = "partial class C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial class C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Fact] public void InstancePropertyInitializer_Leaf_Update() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceFieldInitializer_Leaf_Update1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #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.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceConstructor_DeleteParameterless(string typeKind) { var src1 = "partial " + typeKind + " C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial " + typeKind + " C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial " + typeKind + " C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #endregion } }
1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/EditorFeatures/CSharpTest/EditAndContinue/TopLevelEditingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private readonly bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Fact] public void FieldInitializer_Update1() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update1() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get; } = 1;]@10"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a; [System.Obsolete]C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a { get; } = 1; C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record C { }"; var src2 = @" record C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record struct C { }"; var src2 = @" record struct C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private readonly bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record C { public C() { } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record struct C { public C() { } }"; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_DeleteParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [public C() { b = 3; }]@66", "Delete [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_InsertParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a = 0; }"; var src2 = typeKind + " C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@15 -> [a = 1]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a { get; } = 0; }"; var src2 = typeKind + " C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@11 -> [int a { get; } = 1;]@11"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a; [System.Obsolete]C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a; }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #endregion } }
1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActionsSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; using CodeFixGroupKey = System.Tuple<Microsoft.CodeAnalysis.Diagnostics.DiagnosticData, Microsoft.CodeAnalysis.CodeActions.CodeActionPriority, Microsoft.CodeAnalysis.CodeActions.CodeActionPriority?>; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Provides mutual code action logic for both local and LSP scenarios /// via intermediate interface <see cref="IUnifiedSuggestedAction"/>. /// </summary> internal class UnifiedSuggestedActionsSource { /// <summary> /// Gets, filters, and orders code fixes. /// </summary> public static async ValueTask<ImmutableArray<UnifiedSuggestedActionSet>> GetFilterAndOrderCodeFixesAsync( Workspace workspace, ICodeFixService codeFixService, Document document, TextSpan selection, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken) { // Intentionally switch to a threadpool thread to compute fixes. We do not want to accidentally // run any of this on the UI thread and potentially allow any code to take a dependency on that. var fixes = await Task.Run(() => codeFixService.GetFixesAsync( document, selection, includeSuppressionFixes: true, priority, isBlocking, addOperationScope, cancellationToken), cancellationToken).ConfigureAwait(false); var filteredFixes = fixes.WhereAsArray(c => c.Fixes.Length > 0); var organizedFixes = OrganizeFixes(workspace, filteredFixes); return organizedFixes; } /// <summary> /// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups. /// </summary> private static ImmutableArray<UnifiedSuggestedActionSet> OrganizeFixes( Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections) { var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<UnifiedSuggestedAction>>(); using var _ = ArrayBuilder<CodeFixGroupKey>.GetInstance(out var order); // First group fixes by diagnostic and priority. GroupFixes(workspace, fixCollections, map, order); // Then prioritize between the groups. var prioritizedFixes = PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable(), workspace); return prioritizedFixes; } /// <summary> /// Groups fixes by the diagnostic being addressed by each fix. /// </summary> private static void GroupFixes( Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order) { foreach (var fixCollection in fixCollections) ProcessFixCollection(workspace, map, order, fixCollection); } private static void ProcessFixCollection( Workspace workspace, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection) { var fixes = fixCollection.Fixes; var fixCount = fixes.Length; var nonSupressionCodeFixes = fixes.WhereAsArray(f => !IsTopLevelSuppressionAction(f.Action)); var supressionCodeFixes = fixes.WhereAsArray(f => IsTopLevelSuppressionAction(f.Action)); AddCodeActions(workspace, map, order, fixCollection, GetFixAllSuggestedActionSet, nonSupressionCodeFixes); // Add suppression fixes to the end of a given SuggestedActionSet so that they // always show up last in a group. AddCodeActions(workspace, map, order, fixCollection, GetFixAllSuggestedActionSet, supressionCodeFixes); return; // Local functions UnifiedSuggestedActionSet? GetFixAllSuggestedActionSet(CodeAction codeAction) => GetUnifiedFixAllSuggestedActionSet( codeAction, fixCount, fixCollection.FixAllState, fixCollection.SupportedScopes, fixCollection.FirstDiagnostic, workspace); } private static void AddCodeActions( Workspace workspace, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection, Func<CodeAction, UnifiedSuggestedActionSet?> getFixAllSuggestedActionSet, ImmutableArray<CodeFix> codeFixes) { foreach (var fix in codeFixes) { var unifiedSuggestedAction = GetUnifiedSuggestedAction(fix.Action, fix); AddFix(fix, unifiedSuggestedAction, map, order); } return; // Local functions UnifiedSuggestedAction GetUnifiedSuggestedAction(CodeAction action, CodeFix fix) { if (action.NestedCodeActions.Length > 0) { var nestedActions = action.NestedCodeActions.SelectAsArray( nestedAction => GetUnifiedSuggestedAction(nestedAction, fix)); var set = new UnifiedSuggestedActionSet( categoryName: null, actions: nestedActions, title: null, priority: GetUnifiedSuggestedActionSetPriority(action.Priority), applicableToSpan: fix.PrimaryDiagnostic.Location.SourceSpan); return new UnifiedSuggestedActionWithNestedActions( workspace, action, action.Priority, fixCollection.Provider, ImmutableArray.Create(set)); } else { return new UnifiedCodeFixSuggestedAction( workspace, action, action.Priority, fix, fixCollection.Provider, getFixAllSuggestedActionSet(action)); } } } private static void AddFix( CodeFix fix, UnifiedSuggestedAction suggestedAction, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order) { var groupKey = GetGroupKey(fix); if (!map.ContainsKey(groupKey)) { order.Add(groupKey); map[groupKey] = ImmutableArray.CreateBuilder<UnifiedSuggestedAction>(); } map[groupKey].Add(suggestedAction); return; static CodeFixGroupKey GetGroupKey(CodeFix fix) { var diag = fix.GetPrimaryDiagnosticData(); if (fix.Action is AbstractConfigurationActionWithNestedActions configurationAction) { return new CodeFixGroupKey( diag, configurationAction.Priority, configurationAction.AdditionalPriority); } return new CodeFixGroupKey(diag, fix.Action.Priority, null); } } // If the provided fix all context is non-null and the context's code action Id matches // the given code action's Id, returns the set of fix all occurrences actions associated // with the code action. private static UnifiedSuggestedActionSet? GetUnifiedFixAllSuggestedActionSet( CodeAction action, int actionCount, FixAllState fixAllState, ImmutableArray<FixAllScope> supportedScopes, Diagnostic firstDiagnostic, Workspace workspace) { if (fixAllState == null) { return null; } if (actionCount > 1 && action.EquivalenceKey == null) { return null; } using var fixAllSuggestedActionsDisposer = ArrayBuilder<UnifiedFixAllSuggestedAction>.GetInstance( out var fixAllSuggestedActions); foreach (var scope in supportedScopes) { var fixAllStateForScope = fixAllState.With(scope: scope, codeActionEquivalenceKey: action.EquivalenceKey); var fixAllSuggestedAction = new UnifiedFixAllSuggestedAction( workspace, action, action.Priority, fixAllStateForScope, firstDiagnostic); fixAllSuggestedActions.Add(fixAllSuggestedAction); } return new UnifiedSuggestedActionSet( categoryName: null, actions: fixAllSuggestedActions.ToImmutable(), title: CodeFixesResources.Fix_all_occurrences_in, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: null); } /// <summary> /// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list. /// </summary> /// <remarks> /// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="UnifiedSuggestedActionSet"/>s containing fixes is set to /// <see cref="UnifiedSuggestedActionSetPriority.Medium"/> by default. /// The only exception is the case where a <see cref="UnifiedSuggestedActionSet"/> only contains suppression fixes - /// the priority of such <see cref="UnifiedSuggestedActionSet"/>s is set to /// <see cref="UnifiedSuggestedActionSetPriority.Lowest"/> so that suppression fixes /// always show up last after all other fixes (and refactorings) for the selected line of code. /// </remarks> private static ImmutableArray<UnifiedSuggestedActionSet> PrioritizeFixGroups( ImmutableDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ImmutableArray<CodeFixGroupKey> order, Workspace workspace) { using var _1 = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var nonSuppressionSets); using var _2 = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var suppressionSets); using var _3 = ArrayBuilder<UnifiedSuggestedAction>.GetInstance(out var bulkConfigurationActions); foreach (var groupKey in order) { var actions = map[groupKey]; var nonSuppressionActions = actions.Where(a => !IsTopLevelSuppressionAction(a.OriginalCodeAction)); AddUnifiedSuggestedActionsSet(nonSuppressionActions, groupKey, nonSuppressionSets); var suppressionActions = actions.Where(a => IsTopLevelSuppressionAction(a.OriginalCodeAction) && !IsBulkConfigurationAction(a.OriginalCodeAction)); AddUnifiedSuggestedActionsSet(suppressionActions, groupKey, suppressionSets); bulkConfigurationActions.AddRange(actions.Where(a => IsBulkConfigurationAction(a.OriginalCodeAction))); } var sets = nonSuppressionSets.ToImmutable(); // Append bulk configuration fixes at the end of suppression/configuration fixes. if (bulkConfigurationActions.Count > 0) { var bulkConfigurationSet = new UnifiedSuggestedActionSet( UnifiedPredefinedSuggestedActionCategoryNames.CodeFix, bulkConfigurationActions.ToArray(), title: null, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: null); suppressionSets.Add(bulkConfigurationSet); } if (suppressionSets.Count > 0) { // Wrap the suppression/configuration actions within another top level suggested action // to avoid clutter in the light bulb menu. var suppressOrConfigureCodeAction = new NoChangeAction(CodeFixesResources.Suppress_or_Configure_issues, nameof(CodeFixesResources.Suppress_or_Configure_issues)); var wrappingSuggestedAction = new UnifiedSuggestedActionWithNestedActions( workspace, codeAction: suppressOrConfigureCodeAction, codeActionPriority: suppressOrConfigureCodeAction.Priority, provider: null, nestedActionSets: suppressionSets.ToImmutable()); // Combine the spans and the category of each of the nested suggested actions // to get the span and category for the new top level suggested action. var (span, category) = CombineSpansAndCategory(suppressionSets); var wrappingSet = new UnifiedSuggestedActionSet( category, actions: SpecializedCollections.SingletonEnumerable(wrappingSuggestedAction), title: CodeFixesResources.Suppress_or_Configure_issues, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: span); sets = sets.Add(wrappingSet); } return sets; // Local functions static (TextSpan? span, string category) CombineSpansAndCategory(IEnumerable<UnifiedSuggestedActionSet> sets) { // We are combining the spans and categories of the given set of suggested action sets // to generate a result span containing the spans of individual suggested action sets and // a result category which is the maximum severity category amongst the set var minStart = -1; var maxEnd = -1; var category = UnifiedPredefinedSuggestedActionCategoryNames.CodeFix; foreach (var set in sets) { if (set.ApplicableToSpan.HasValue) { var currentStart = set.ApplicableToSpan.Value.Start; var currentEnd = set.ApplicableToSpan.Value.End; if (minStart == -1 || currentStart < minStart) { minStart = currentStart; } if (maxEnd == -1 || currentEnd > maxEnd) { maxEnd = currentEnd; } } Debug.Assert(set.CategoryName is UnifiedPredefinedSuggestedActionCategoryNames.CodeFix or UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix); // If this set contains an error fix, then change the result category to ErrorFix if (set.CategoryName == UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix) { category = UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix; } } var combinedSpan = minStart >= 0 ? TextSpan.FromBounds(minStart, maxEnd) : (TextSpan?)null; return (combinedSpan, category); } } private static void AddUnifiedSuggestedActionsSet( IEnumerable<UnifiedSuggestedAction> actions, CodeFixGroupKey groupKey, ArrayBuilder<UnifiedSuggestedActionSet> sets) { foreach (var group in actions.GroupBy(a => a.CodeActionPriority)) { var priority = GetUnifiedSuggestedActionSetPriority(group.Key); // diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics Debug.Assert(groupKey.Item1.HasTextSpan); var category = GetFixCategory(groupKey.Item1.Severity); sets.Add(new UnifiedSuggestedActionSet( category, group, title: null, priority: priority, applicableToSpan: groupKey.Item1.GetTextSpan())); } } private static string GetFixCategory(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: case DiagnosticSeverity.Info: case DiagnosticSeverity.Warning: return UnifiedPredefinedSuggestedActionCategoryNames.CodeFix; case DiagnosticSeverity.Error: return UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix; default: throw ExceptionUtilities.Unreachable; } } private static bool IsTopLevelSuppressionAction(CodeAction action) => action is AbstractConfigurationActionWithNestedActions; private static bool IsBulkConfigurationAction(CodeAction action) => (action as AbstractConfigurationActionWithNestedActions)?.IsBulkConfigurationAction == true; /// <summary> /// Gets, filters, and orders code refactorings. /// </summary> public static async Task<ImmutableArray<UnifiedSuggestedActionSet>> GetFilterAndOrderCodeRefactoringsAsync( Workspace workspace, ICodeRefactoringService codeRefactoringService, Document document, TextSpan selection, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, bool filterOutsideSelection, CancellationToken cancellationToken) { // It may seem strange that we kick off a task, but then immediately 'Wait' on // it. However, it's deliberate. We want to make sure that the code runs on // the background so that no one takes an accidentally dependency on running on // the UI thread. var refactorings = await Task.Run( () => codeRefactoringService.GetRefactoringsAsync( document, selection, priority, isBlocking, addOperationScope, cancellationToken), cancellationToken).ConfigureAwait(false); var filteredRefactorings = FilterOnAnyThread(refactorings, selection, filterOutsideSelection); return filteredRefactorings.SelectAsArray( r => OrganizeRefactorings(workspace, r)); } private static ImmutableArray<CodeRefactoring> FilterOnAnyThread( ImmutableArray<CodeRefactoring> refactorings, TextSpan selection, bool filterOutsideSelection) => refactorings.Select(r => FilterOnAnyThread(r, selection, filterOutsideSelection)).WhereNotNull().ToImmutableArray(); private static CodeRefactoring? FilterOnAnyThread( CodeRefactoring refactoring, TextSpan selection, bool filterOutsideSelection) { var actions = refactoring.CodeActions.WhereAsArray(IsActionAndSpanApplicable); return actions.Length == 0 ? null : actions.Length == refactoring.CodeActions.Length ? refactoring : new CodeRefactoring(refactoring.Provider, actions); bool IsActionAndSpanApplicable((CodeAction action, TextSpan? applicableSpan) actionAndSpan) { if (filterOutsideSelection) { // Filter out refactorings with applicable span outside the selection span. if (!actionAndSpan.applicableSpan.HasValue || !selection.IntersectsWith(actionAndSpan.applicableSpan.Value)) { return false; } } return true; } } /// <summary> /// Arrange refactorings into groups. /// </summary> /// <remarks> /// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="UnifiedSuggestedActionSet"/>s containing refactorings is set to /// <see cref="UnifiedSuggestedActionSetPriority.Low"/> and should show up after fixes but before /// suppression fixes in the light bulb menu. /// </remarks> private static UnifiedSuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring) { using var refactoringSuggestedActionsDisposer = ArrayBuilder<UnifiedSuggestedAction>.GetInstance( out var refactoringSuggestedActions); foreach (var codeAction in refactoring.CodeActions) { if (codeAction.action.NestedCodeActions.Length > 0) { var nestedActions = codeAction.action.NestedCodeActions.SelectAsArray( na => new UnifiedCodeRefactoringSuggestedAction( workspace, na, na.Priority, refactoring.Provider)); var set = new UnifiedSuggestedActionSet( categoryName: null, actions: nestedActions, title: null, priority: GetUnifiedSuggestedActionSetPriority(codeAction.action.Priority), applicableToSpan: codeAction.applicableToSpan); refactoringSuggestedActions.Add( new UnifiedSuggestedActionWithNestedActions( workspace, codeAction.action, codeAction.action.Priority, refactoring.Provider, ImmutableArray.Create(set))); } else { refactoringSuggestedActions.Add( new UnifiedCodeRefactoringSuggestedAction( workspace, codeAction.action, codeAction.action.Priority, refactoring.Provider)); } } var actions = refactoringSuggestedActions.ToImmutable(); // An action set: // - gets the the same priority as the highest priority action within in. // - gets `applicableToSpan` of the first action: // - E.g. the `applicableToSpan` closest to current selection might be a more correct // choice. All actions created by one Refactoring have usually the same `applicableSpan` // and therefore the complexity of determining the closest one isn't worth the benefit // of slightly more correct orderings in certain edge cases. return new UnifiedSuggestedActionSet( UnifiedPredefinedSuggestedActionCategoryNames.Refactoring, actions: actions, title: null, priority: GetUnifiedSuggestedActionSetPriority(actions.Max(a => a.CodeActionPriority)), applicableToSpan: refactoring.CodeActions.FirstOrDefault().applicableToSpan); } private static UnifiedSuggestedActionSetPriority GetUnifiedSuggestedActionSetPriority(CodeActionPriority key) => key switch { CodeActionPriority.Lowest => UnifiedSuggestedActionSetPriority.Lowest, CodeActionPriority.Low => UnifiedSuggestedActionSetPriority.Low, CodeActionPriority.Medium => UnifiedSuggestedActionSetPriority.Medium, CodeActionPriority.High => UnifiedSuggestedActionSetPriority.High, _ => throw new InvalidOperationException(), }; /// <summary> /// Filters and orders the code fix sets and code refactoring sets amongst each other. /// Should be called with the results from <see cref="GetFilterAndOrderCodeFixesAsync"/> /// and <see cref="GetFilterAndOrderCodeRefactoringsAsync"/>. /// </summary> public static ImmutableArray<UnifiedSuggestedActionSet> FilterAndOrderActionSets( ImmutableArray<UnifiedSuggestedActionSet> fixes, ImmutableArray<UnifiedSuggestedActionSet> refactorings, TextSpan? selectionOpt) { // Get the initial set of action sets, with refactorings and fixes appropriately // ordered against each other. var result = GetInitiallyOrderedActionSets(selectionOpt, fixes, refactorings); if (result.IsEmpty) return ImmutableArray<UnifiedSuggestedActionSet>.Empty; // Now that we have the entire set of action sets, inline, sort and filter // them appropriately against each other. var allActionSets = InlineActionSetsIfDesirable(result); var orderedActionSets = OrderActionSets(allActionSets, selectionOpt); var filteredSets = FilterActionSetsByTitle(orderedActionSets); return filteredSets; } private static ImmutableArray<UnifiedSuggestedActionSet> GetInitiallyOrderedActionSets( TextSpan? selectionOpt, ImmutableArray<UnifiedSuggestedActionSet> fixes, ImmutableArray<UnifiedSuggestedActionSet> refactorings) { // First, order refactorings based on the order the providers actually gave for // their actions. This way, a low pri refactoring always shows after a medium pri // refactoring, no matter what we do below. refactorings = OrderActionSets(refactorings, selectionOpt); // If there's a selection, it's likely the user is trying to perform some operation // directly on that operation (like 'extract method'). Prioritize refactorings over // fixes in that case. Otherwise, it's likely that the user is just on some error // and wants to fix it (in which case, prioritize fixes). if (selectionOpt?.Length > 0) { // There was a selection. Treat refactorings as more important than fixes. // Note: we still will sort after this. So any high pri fixes will come to the // front. Any low-pri refactorings will go to the end. return refactorings.Concat(fixes); } else { // No selection. Treat all medium and low pri refactorings as low priority, and // place after fixes. Even a low pri fixes will be above what was *originally* // a medium pri refactoring. // // Note: we do not do this for *high* pri refactorings (like 'rename'). These // are still very important and need to stay at the top (though still after high // pri fixes). var highPriRefactorings = refactorings.WhereAsArray( s => s.Priority == UnifiedSuggestedActionSetPriority.High); var nonHighPriRefactorings = refactorings.WhereAsArray( s => s.Priority != UnifiedSuggestedActionSetPriority.High) .SelectAsArray(s => WithPriority(s, UnifiedSuggestedActionSetPriority.Low)); var highPriFixes = fixes.WhereAsArray(s => s.Priority == UnifiedSuggestedActionSetPriority.High); var nonHighPriFixes = fixes.WhereAsArray(s => s.Priority != UnifiedSuggestedActionSetPriority.High); return highPriFixes.Concat(highPriRefactorings).Concat(nonHighPriFixes).Concat(nonHighPriRefactorings); } } private static ImmutableArray<UnifiedSuggestedActionSet> OrderActionSets( ImmutableArray<UnifiedSuggestedActionSet> actionSets, TextSpan? selectionOpt) { return actionSets.OrderByDescending(s => s.Priority) .ThenBy(s => s, new UnifiedSuggestedActionSetComparer(selectionOpt)) .ToImmutableArray(); } private static UnifiedSuggestedActionSet WithPriority( UnifiedSuggestedActionSet set, UnifiedSuggestedActionSetPriority priority) => new(set.CategoryName, set.Actions, set.Title, priority, set.ApplicableToSpan); private static ImmutableArray<UnifiedSuggestedActionSet> InlineActionSetsIfDesirable( ImmutableArray<UnifiedSuggestedActionSet> allActionSets) { // If we only have a single set of items, and that set only has three max suggestion // offered. Then we can consider inlining any nested actions into the top level list. // (but we only do this if the parent of the nested actions isn't invokable itself). if (allActionSets.Sum(a => a.Actions.Count()) > 3) { return allActionSets; } return allActionSets.SelectAsArray(InlineActions); } private static UnifiedSuggestedActionSet InlineActions(UnifiedSuggestedActionSet actionSet) { using var newActionsDisposer = ArrayBuilder<IUnifiedSuggestedAction>.GetInstance(out var newActions); foreach (var action in actionSet.Actions) { var actionWithNestedActions = action as UnifiedSuggestedActionWithNestedActions; // Only inline if the underlying code action allows it. if (actionWithNestedActions?.OriginalCodeAction.IsInlinable == true) { newActions.AddRange(actionWithNestedActions.NestedActionSets.SelectMany(set => set.Actions)); } else { newActions.Add(action); } } return new UnifiedSuggestedActionSet( actionSet.CategoryName, newActions.ToImmutable(), actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan); } private static ImmutableArray<UnifiedSuggestedActionSet> FilterActionSetsByTitle( ImmutableArray<UnifiedSuggestedActionSet> allActionSets) { using var resultDisposer = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var result); var seenTitles = new HashSet<string>(); foreach (var set in allActionSets) { var filteredSet = FilterActionSetByTitle(set, seenTitles); if (filteredSet != null) { result.Add(filteredSet); } } return result.ToImmutable(); } private static UnifiedSuggestedActionSet? FilterActionSetByTitle(UnifiedSuggestedActionSet set, HashSet<string> seenTitles) { using var actionsDisposer = ArrayBuilder<IUnifiedSuggestedAction>.GetInstance(out var actions); foreach (var action in set.Actions) { if (seenTitles.Add(action.OriginalCodeAction.Title)) { actions.Add(action); } } return actions.Count == 0 ? null : new UnifiedSuggestedActionSet(set.CategoryName, actions.ToImmutable(), set.Title, set.Priority, set.ApplicableToSpan); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; using CodeFixGroupKey = System.Tuple<Microsoft.CodeAnalysis.Diagnostics.DiagnosticData, Microsoft.CodeAnalysis.CodeActions.CodeActionPriority, Microsoft.CodeAnalysis.CodeActions.CodeActionPriority?>; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Provides mutual code action logic for both local and LSP scenarios /// via intermediate interface <see cref="IUnifiedSuggestedAction"/>. /// </summary> internal class UnifiedSuggestedActionsSource { /// <summary> /// Gets, filters, and orders code fixes. /// </summary> public static async ValueTask<ImmutableArray<UnifiedSuggestedActionSet>> GetFilterAndOrderCodeFixesAsync( Workspace workspace, ICodeFixService codeFixService, Document document, TextSpan selection, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken) { // Intentionally switch to a threadpool thread to compute fixes. We do not want to accidentally // run any of this on the UI thread and potentially allow any code to take a dependency on that. var fixes = await Task.Run(() => codeFixService.GetFixesAsync( document, selection, includeSuppressionFixes: true, priority, isBlocking, addOperationScope, cancellationToken), cancellationToken).ConfigureAwait(false); var filteredFixes = fixes.WhereAsArray(c => c.Fixes.Length > 0); var organizedFixes = OrganizeFixes(workspace, filteredFixes); return organizedFixes; } /// <summary> /// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups. /// </summary> private static ImmutableArray<UnifiedSuggestedActionSet> OrganizeFixes( Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections) { var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<UnifiedSuggestedAction>>(); using var _ = ArrayBuilder<CodeFixGroupKey>.GetInstance(out var order); // First group fixes by diagnostic and priority. GroupFixes(workspace, fixCollections, map, order); // Then prioritize between the groups. var prioritizedFixes = PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable(), workspace); return prioritizedFixes; } /// <summary> /// Groups fixes by the diagnostic being addressed by each fix. /// </summary> private static void GroupFixes( Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order) { foreach (var fixCollection in fixCollections) ProcessFixCollection(workspace, map, order, fixCollection); } private static void ProcessFixCollection( Workspace workspace, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection) { var fixes = fixCollection.Fixes; var fixCount = fixes.Length; var nonSupressionCodeFixes = fixes.WhereAsArray(f => !IsTopLevelSuppressionAction(f.Action)); var supressionCodeFixes = fixes.WhereAsArray(f => IsTopLevelSuppressionAction(f.Action)); AddCodeActions(workspace, map, order, fixCollection, GetFixAllSuggestedActionSet, nonSupressionCodeFixes); // Add suppression fixes to the end of a given SuggestedActionSet so that they // always show up last in a group. AddCodeActions(workspace, map, order, fixCollection, GetFixAllSuggestedActionSet, supressionCodeFixes); return; // Local functions UnifiedSuggestedActionSet? GetFixAllSuggestedActionSet(CodeAction codeAction) => GetUnifiedFixAllSuggestedActionSet( codeAction, fixCount, fixCollection.FixAllState, fixCollection.SupportedScopes, fixCollection.FirstDiagnostic, workspace); } private static void AddCodeActions( Workspace workspace, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection, Func<CodeAction, UnifiedSuggestedActionSet?> getFixAllSuggestedActionSet, ImmutableArray<CodeFix> codeFixes) { foreach (var fix in codeFixes) { var unifiedSuggestedAction = GetUnifiedSuggestedAction(fix.Action, fix); AddFix(fix, unifiedSuggestedAction, map, order); } return; // Local functions UnifiedSuggestedAction GetUnifiedSuggestedAction(CodeAction action, CodeFix fix) { if (action.NestedCodeActions.Length > 0) { var nestedActions = action.NestedCodeActions.SelectAsArray( nestedAction => GetUnifiedSuggestedAction(nestedAction, fix)); var set = new UnifiedSuggestedActionSet( categoryName: null, actions: nestedActions, title: null, priority: GetUnifiedSuggestedActionSetPriority(action.Priority), applicableToSpan: fix.PrimaryDiagnostic.Location.SourceSpan); return new UnifiedSuggestedActionWithNestedActions( workspace, action, action.Priority, fixCollection.Provider, ImmutableArray.Create(set)); } else { return new UnifiedCodeFixSuggestedAction( workspace, action, action.Priority, fix, fixCollection.Provider, getFixAllSuggestedActionSet(action)); } } } private static void AddFix( CodeFix fix, UnifiedSuggestedAction suggestedAction, IDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ArrayBuilder<CodeFixGroupKey> order) { var groupKey = GetGroupKey(fix); if (!map.ContainsKey(groupKey)) { order.Add(groupKey); map[groupKey] = ImmutableArray.CreateBuilder<UnifiedSuggestedAction>(); } map[groupKey].Add(suggestedAction); return; static CodeFixGroupKey GetGroupKey(CodeFix fix) { var diag = fix.GetPrimaryDiagnosticData(); if (fix.Action is AbstractConfigurationActionWithNestedActions configurationAction) { return new CodeFixGroupKey( diag, configurationAction.Priority, configurationAction.AdditionalPriority); } return new CodeFixGroupKey(diag, fix.Action.Priority, null); } } // If the provided fix all context is non-null and the context's code action Id matches // the given code action's Id, returns the set of fix all occurrences actions associated // with the code action. private static UnifiedSuggestedActionSet? GetUnifiedFixAllSuggestedActionSet( CodeAction action, int actionCount, FixAllState fixAllState, ImmutableArray<FixAllScope> supportedScopes, Diagnostic firstDiagnostic, Workspace workspace) { if (fixAllState == null) { return null; } if (actionCount > 1 && action.EquivalenceKey == null) { return null; } using var fixAllSuggestedActionsDisposer = ArrayBuilder<UnifiedFixAllSuggestedAction>.GetInstance( out var fixAllSuggestedActions); foreach (var scope in supportedScopes) { var fixAllStateForScope = fixAllState.With(scope: scope, codeActionEquivalenceKey: action.EquivalenceKey); var fixAllSuggestedAction = new UnifiedFixAllSuggestedAction( workspace, action, action.Priority, fixAllStateForScope, firstDiagnostic); fixAllSuggestedActions.Add(fixAllSuggestedAction); } return new UnifiedSuggestedActionSet( categoryName: null, actions: fixAllSuggestedActions.ToImmutable(), title: CodeFixesResources.Fix_all_occurrences_in, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: null); } /// <summary> /// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list. /// </summary> /// <remarks> /// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="UnifiedSuggestedActionSet"/>s containing fixes is set to /// <see cref="UnifiedSuggestedActionSetPriority.Medium"/> by default. /// The only exception is the case where a <see cref="UnifiedSuggestedActionSet"/> only contains suppression fixes - /// the priority of such <see cref="UnifiedSuggestedActionSet"/>s is set to /// <see cref="UnifiedSuggestedActionSetPriority.Lowest"/> so that suppression fixes /// always show up last after all other fixes (and refactorings) for the selected line of code. /// </remarks> private static ImmutableArray<UnifiedSuggestedActionSet> PrioritizeFixGroups( ImmutableDictionary<CodeFixGroupKey, IList<UnifiedSuggestedAction>> map, ImmutableArray<CodeFixGroupKey> order, Workspace workspace) { using var _1 = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var nonSuppressionSets); using var _2 = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var suppressionSets); using var _3 = ArrayBuilder<UnifiedSuggestedAction>.GetInstance(out var bulkConfigurationActions); foreach (var groupKey in order) { var actions = map[groupKey]; var nonSuppressionActions = actions.Where(a => !IsTopLevelSuppressionAction(a.OriginalCodeAction)); AddUnifiedSuggestedActionsSet(nonSuppressionActions, groupKey, nonSuppressionSets); var suppressionActions = actions.Where(a => IsTopLevelSuppressionAction(a.OriginalCodeAction) && !IsBulkConfigurationAction(a.OriginalCodeAction)); AddUnifiedSuggestedActionsSet(suppressionActions, groupKey, suppressionSets); bulkConfigurationActions.AddRange(actions.Where(a => IsBulkConfigurationAction(a.OriginalCodeAction))); } var sets = nonSuppressionSets.ToImmutable(); // Append bulk configuration fixes at the end of suppression/configuration fixes. if (bulkConfigurationActions.Count > 0) { var bulkConfigurationSet = new UnifiedSuggestedActionSet( UnifiedPredefinedSuggestedActionCategoryNames.CodeFix, bulkConfigurationActions.ToArray(), title: null, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: null); suppressionSets.Add(bulkConfigurationSet); } if (suppressionSets.Count > 0) { // Wrap the suppression/configuration actions within another top level suggested action // to avoid clutter in the light bulb menu. var suppressOrConfigureCodeAction = new NoChangeAction(CodeFixesResources.Suppress_or_Configure_issues, nameof(CodeFixesResources.Suppress_or_Configure_issues)); var wrappingSuggestedAction = new UnifiedSuggestedActionWithNestedActions( workspace, codeAction: suppressOrConfigureCodeAction, codeActionPriority: suppressOrConfigureCodeAction.Priority, provider: null, nestedActionSets: suppressionSets.ToImmutable()); // Combine the spans and the category of each of the nested suggested actions // to get the span and category for the new top level suggested action. var (span, category) = CombineSpansAndCategory(suppressionSets); var wrappingSet = new UnifiedSuggestedActionSet( category, actions: SpecializedCollections.SingletonEnumerable(wrappingSuggestedAction), title: CodeFixesResources.Suppress_or_Configure_issues, priority: UnifiedSuggestedActionSetPriority.Lowest, applicableToSpan: span); sets = sets.Add(wrappingSet); } return sets; // Local functions static (TextSpan? span, string category) CombineSpansAndCategory(IEnumerable<UnifiedSuggestedActionSet> sets) { // We are combining the spans and categories of the given set of suggested action sets // to generate a result span containing the spans of individual suggested action sets and // a result category which is the maximum severity category amongst the set var minStart = -1; var maxEnd = -1; var category = UnifiedPredefinedSuggestedActionCategoryNames.CodeFix; foreach (var set in sets) { if (set.ApplicableToSpan.HasValue) { var currentStart = set.ApplicableToSpan.Value.Start; var currentEnd = set.ApplicableToSpan.Value.End; if (minStart == -1 || currentStart < minStart) { minStart = currentStart; } if (maxEnd == -1 || currentEnd > maxEnd) { maxEnd = currentEnd; } } Debug.Assert(set.CategoryName is UnifiedPredefinedSuggestedActionCategoryNames.CodeFix or UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix); // If this set contains an error fix, then change the result category to ErrorFix if (set.CategoryName == UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix) { category = UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix; } } var combinedSpan = minStart >= 0 ? TextSpan.FromBounds(minStart, maxEnd) : (TextSpan?)null; return (combinedSpan, category); } } private static void AddUnifiedSuggestedActionsSet( IEnumerable<UnifiedSuggestedAction> actions, CodeFixGroupKey groupKey, ArrayBuilder<UnifiedSuggestedActionSet> sets) { foreach (var group in actions.GroupBy(a => a.CodeActionPriority)) { var priority = GetUnifiedSuggestedActionSetPriority(group.Key); // diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics Debug.Assert(groupKey.Item1.HasTextSpan); var category = GetFixCategory(groupKey.Item1.Severity); sets.Add(new UnifiedSuggestedActionSet( category, group, title: null, priority: priority, applicableToSpan: groupKey.Item1.GetTextSpan())); } } private static string GetFixCategory(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: case DiagnosticSeverity.Info: case DiagnosticSeverity.Warning: return UnifiedPredefinedSuggestedActionCategoryNames.CodeFix; case DiagnosticSeverity.Error: return UnifiedPredefinedSuggestedActionCategoryNames.ErrorFix; default: throw ExceptionUtilities.Unreachable; } } private static bool IsTopLevelSuppressionAction(CodeAction action) => action is AbstractConfigurationActionWithNestedActions; private static bool IsBulkConfigurationAction(CodeAction action) => (action as AbstractConfigurationActionWithNestedActions)?.IsBulkConfigurationAction == true; /// <summary> /// Gets, filters, and orders code refactorings. /// </summary> public static async Task<ImmutableArray<UnifiedSuggestedActionSet>> GetFilterAndOrderCodeRefactoringsAsync( Workspace workspace, ICodeRefactoringService codeRefactoringService, Document document, TextSpan selection, CodeActionRequestPriority priority, bool isBlocking, Func<string, IDisposable?> addOperationScope, bool filterOutsideSelection, CancellationToken cancellationToken) { // It may seem strange that we kick off a task, but then immediately 'Wait' on // it. However, it's deliberate. We want to make sure that the code runs on // the background so that no one takes an accidentally dependency on running on // the UI thread. var refactorings = await Task.Run( () => codeRefactoringService.GetRefactoringsAsync( document, selection, priority, isBlocking, addOperationScope, cancellationToken), cancellationToken).ConfigureAwait(false); var filteredRefactorings = FilterOnAnyThread(refactorings, selection, filterOutsideSelection); return filteredRefactorings.SelectAsArray( r => OrganizeRefactorings(workspace, r)); } private static ImmutableArray<CodeRefactoring> FilterOnAnyThread( ImmutableArray<CodeRefactoring> refactorings, TextSpan selection, bool filterOutsideSelection) => refactorings.Select(r => FilterOnAnyThread(r, selection, filterOutsideSelection)).WhereNotNull().ToImmutableArray(); private static CodeRefactoring? FilterOnAnyThread( CodeRefactoring refactoring, TextSpan selection, bool filterOutsideSelection) { var actions = refactoring.CodeActions.WhereAsArray(IsActionAndSpanApplicable); return actions.Length == 0 ? null : actions.Length == refactoring.CodeActions.Length ? refactoring : new CodeRefactoring(refactoring.Provider, actions); bool IsActionAndSpanApplicable((CodeAction action, TextSpan? applicableSpan) actionAndSpan) { if (filterOutsideSelection) { // Filter out refactorings with applicable span outside the selection span. if (!actionAndSpan.applicableSpan.HasValue || !selection.IntersectsWith(actionAndSpan.applicableSpan.Value)) { return false; } } return true; } } /// <summary> /// Arrange refactorings into groups. /// </summary> /// <remarks> /// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="UnifiedSuggestedActionSet"/>s containing refactorings is set to /// <see cref="UnifiedSuggestedActionSetPriority.Low"/> and should show up after fixes but before /// suppression fixes in the light bulb menu. /// </remarks> private static UnifiedSuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring) { using var refactoringSuggestedActionsDisposer = ArrayBuilder<UnifiedSuggestedAction>.GetInstance( out var refactoringSuggestedActions); foreach (var codeAction in refactoring.CodeActions) { if (codeAction.action.NestedCodeActions.Length > 0) { var nestedActions = codeAction.action.NestedCodeActions.SelectAsArray( na => new UnifiedCodeRefactoringSuggestedAction( workspace, na, na.Priority, refactoring.Provider)); var set = new UnifiedSuggestedActionSet( categoryName: null, actions: nestedActions, title: null, priority: GetUnifiedSuggestedActionSetPriority(codeAction.action.Priority), applicableToSpan: codeAction.applicableToSpan); refactoringSuggestedActions.Add( new UnifiedSuggestedActionWithNestedActions( workspace, codeAction.action, codeAction.action.Priority, refactoring.Provider, ImmutableArray.Create(set))); } else { refactoringSuggestedActions.Add( new UnifiedCodeRefactoringSuggestedAction( workspace, codeAction.action, codeAction.action.Priority, refactoring.Provider)); } } var actions = refactoringSuggestedActions.ToImmutable(); // An action set: // - gets the the same priority as the highest priority action within in. // - gets `applicableToSpan` of the first action: // - E.g. the `applicableToSpan` closest to current selection might be a more correct // choice. All actions created by one Refactoring have usually the same `applicableSpan` // and therefore the complexity of determining the closest one isn't worth the benefit // of slightly more correct orderings in certain edge cases. return new UnifiedSuggestedActionSet( UnifiedPredefinedSuggestedActionCategoryNames.Refactoring, actions: actions, title: null, priority: GetUnifiedSuggestedActionSetPriority(actions.Max(a => a.CodeActionPriority)), applicableToSpan: refactoring.CodeActions.FirstOrDefault().applicableToSpan); } private static UnifiedSuggestedActionSetPriority GetUnifiedSuggestedActionSetPriority(CodeActionPriority key) => key switch { CodeActionPriority.Lowest => UnifiedSuggestedActionSetPriority.Lowest, CodeActionPriority.Low => UnifiedSuggestedActionSetPriority.Low, CodeActionPriority.Medium => UnifiedSuggestedActionSetPriority.Medium, CodeActionPriority.High => UnifiedSuggestedActionSetPriority.High, _ => throw new InvalidOperationException(), }; /// <summary> /// Filters and orders the code fix sets and code refactoring sets amongst each other. /// Should be called with the results from <see cref="GetFilterAndOrderCodeFixesAsync"/> /// and <see cref="GetFilterAndOrderCodeRefactoringsAsync"/>. /// </summary> public static ImmutableArray<UnifiedSuggestedActionSet> FilterAndOrderActionSets( ImmutableArray<UnifiedSuggestedActionSet> fixes, ImmutableArray<UnifiedSuggestedActionSet> refactorings, TextSpan? selectionOpt) { // Get the initial set of action sets, with refactorings and fixes appropriately // ordered against each other. var result = GetInitiallyOrderedActionSets(selectionOpt, fixes, refactorings); if (result.IsEmpty) return ImmutableArray<UnifiedSuggestedActionSet>.Empty; // Now that we have the entire set of action sets, inline, sort and filter // them appropriately against each other. var allActionSets = InlineActionSetsIfDesirable(result); var orderedActionSets = OrderActionSets(allActionSets, selectionOpt); var filteredSets = FilterActionSetsByTitle(orderedActionSets); return filteredSets; } private static ImmutableArray<UnifiedSuggestedActionSet> GetInitiallyOrderedActionSets( TextSpan? selectionOpt, ImmutableArray<UnifiedSuggestedActionSet> fixes, ImmutableArray<UnifiedSuggestedActionSet> refactorings) { // First, order refactorings based on the order the providers actually gave for // their actions. This way, a low pri refactoring always shows after a medium pri // refactoring, no matter what we do below. refactorings = OrderActionSets(refactorings, selectionOpt); // If there's a selection, it's likely the user is trying to perform some operation // directly on that operation (like 'extract method'). Prioritize refactorings over // fixes in that case. Otherwise, it's likely that the user is just on some error // and wants to fix it (in which case, prioritize fixes). if (selectionOpt?.Length > 0) { // There was a selection. Treat refactorings as more important than fixes. // Note: we still will sort after this. So any high pri fixes will come to the // front. Any low-pri refactorings will go to the end. return refactorings.Concat(fixes); } else { // No selection. Treat all medium and low pri refactorings as low priority, and // place after fixes. Even a low pri fixes will be above what was *originally* // a medium pri refactoring. // // Note: we do not do this for *high* pri refactorings (like 'rename'). These // are still very important and need to stay at the top (though still after high // pri fixes). var highPriRefactorings = refactorings.WhereAsArray( s => s.Priority == UnifiedSuggestedActionSetPriority.High); var nonHighPriRefactorings = refactorings.WhereAsArray( s => s.Priority != UnifiedSuggestedActionSetPriority.High) .SelectAsArray(s => WithPriority(s, UnifiedSuggestedActionSetPriority.Low)); var highPriFixes = fixes.WhereAsArray(s => s.Priority == UnifiedSuggestedActionSetPriority.High); var nonHighPriFixes = fixes.WhereAsArray(s => s.Priority != UnifiedSuggestedActionSetPriority.High); return highPriFixes.Concat(highPriRefactorings).Concat(nonHighPriFixes).Concat(nonHighPriRefactorings); } } private static ImmutableArray<UnifiedSuggestedActionSet> OrderActionSets( ImmutableArray<UnifiedSuggestedActionSet> actionSets, TextSpan? selectionOpt) { return actionSets.OrderByDescending(s => s.Priority) .ThenBy(s => s, new UnifiedSuggestedActionSetComparer(selectionOpt)) .ToImmutableArray(); } private static UnifiedSuggestedActionSet WithPriority( UnifiedSuggestedActionSet set, UnifiedSuggestedActionSetPriority priority) => new(set.CategoryName, set.Actions, set.Title, priority, set.ApplicableToSpan); private static ImmutableArray<UnifiedSuggestedActionSet> InlineActionSetsIfDesirable( ImmutableArray<UnifiedSuggestedActionSet> allActionSets) { // If we only have a single set of items, and that set only has three max suggestion // offered. Then we can consider inlining any nested actions into the top level list. // (but we only do this if the parent of the nested actions isn't invokable itself). if (allActionSets.Sum(a => a.Actions.Count()) > 3) { return allActionSets; } return allActionSets.SelectAsArray(InlineActions); } private static UnifiedSuggestedActionSet InlineActions(UnifiedSuggestedActionSet actionSet) { using var newActionsDisposer = ArrayBuilder<IUnifiedSuggestedAction>.GetInstance(out var newActions); foreach (var action in actionSet.Actions) { var actionWithNestedActions = action as UnifiedSuggestedActionWithNestedActions; // Only inline if the underlying code action allows it. if (actionWithNestedActions?.OriginalCodeAction.IsInlinable == true) { newActions.AddRange(actionWithNestedActions.NestedActionSets.SelectMany(set => set.Actions)); } else { newActions.Add(action); } } return new UnifiedSuggestedActionSet( actionSet.CategoryName, newActions.ToImmutable(), actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan); } private static ImmutableArray<UnifiedSuggestedActionSet> FilterActionSetsByTitle( ImmutableArray<UnifiedSuggestedActionSet> allActionSets) { using var resultDisposer = ArrayBuilder<UnifiedSuggestedActionSet>.GetInstance(out var result); var seenTitles = new HashSet<string>(); foreach (var set in allActionSets) { var filteredSet = FilterActionSetByTitle(set, seenTitles); if (filteredSet != null) { result.Add(filteredSet); } } return result.ToImmutable(); } private static UnifiedSuggestedActionSet? FilterActionSetByTitle(UnifiedSuggestedActionSet set, HashSet<string> seenTitles) { using var actionsDisposer = ArrayBuilder<IUnifiedSuggestedAction>.GetInstance(out var actions); foreach (var action in set.Actions) { if (seenTitles.Add(action.OriginalCodeAction.Title)) { actions.Add(action); } } return actions.Count == 0 ? null : new UnifiedSuggestedActionSet(set.CategoryName, actions.ToImmutable(), set.Title, set.Priority, set.ApplicableToSpan); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/AbstractCodeMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeMember : AbstractKeyedCodeElement { internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } protected SyntaxNode GetContainingTypeNode() => LookupNode().Ancestors().Where(CodeModelService.IsType).FirstOrDefault(); public override object Parent { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string Comment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetComment(node); } set { UpdateNode(FileCodeModel.UpdateComment, value); } } public string DocComment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetDocComment(node); } set { UpdateNode(FileCodeModel.UpdateDocComment, value); } } public bool IsGeneric { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsGeneric(node); } } public bool IsShared { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsShared(node, LookupSymbol()); } set { UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateIsShared, value); } } public bool MustImplement { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetMustImplement(node); } set { UpdateNode(FileCodeModel.UpdateMustImplement, value); } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetOverrideKind(node); } set { UpdateNode(FileCodeModel.UpdateOverrideKind, value); } } internal virtual ImmutableArray<SyntaxNode> GetParameters() => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElements Parameters { get { return ParameterCollection.Create(this.State, this); } } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { return FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after adding a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var parameter = FileCodeModel.AddParameter(this, node, name, type, position); ReacquireNodeKey(nodePath, CancellationToken.None); return parameter; }); } public void RemoveParameter(object element) { FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after removing a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Parameters.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); ReacquireNodeKey(nodePath, CancellationToken.None); }); } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, 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; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeMember : AbstractKeyedCodeElement { internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeMember( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } protected SyntaxNode GetContainingTypeNode() => LookupNode().Ancestors().Where(CodeModelService.IsType).FirstOrDefault(); public override object Parent { get { var containingTypeNode = GetContainingTypeNode(); if (containingTypeNode == null) { throw Exceptions.ThrowEUnexpected(); } return FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingTypeNode); } } public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string Comment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetComment(node); } set { UpdateNode(FileCodeModel.UpdateComment, value); } } public string DocComment { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetDocComment(node); } set { UpdateNode(FileCodeModel.UpdateDocComment, value); } } public bool IsGeneric { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsGeneric(node); } } public bool IsShared { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetIsShared(node, LookupSymbol()); } set { UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateIsShared, value); } } public bool MustImplement { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetMustImplement(node); } set { UpdateNode(FileCodeModel.UpdateMustImplement, value); } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { var node = CodeModelService.GetNodeWithModifiers(LookupNode()); return CodeModelService.GetOverrideKind(node); } set { UpdateNode(FileCodeModel.UpdateOverrideKind, value); } } internal virtual ImmutableArray<SyntaxNode> GetParameters() => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElements Parameters { get { return ParameterCollection.Create(this.State, this); } } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { return FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after adding a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var parameter = FileCodeModel.AddParameter(this, node, name, type, position); ReacquireNodeKey(nodePath, CancellationToken.None); return parameter; }); } public void RemoveParameter(object element) { FileCodeModel.EnsureEditor(() => { // The parameters are part of the node key, so we need to update it // after removing a parameter. var node = LookupNode(); var nodePath = new SyntaxPath(node); var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Parameters.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); ReacquireNodeKey(nodePath, CancellationToken.None); }); } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, position); }); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Features/CSharp/Portable/ImplementInterface/CSharpImplementExplicitlyCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ImplementInterface { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly), Shared] internal class CSharpImplementExplicitlyCodeRefactoringProvider : AbstractChangeImplementionCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpImplementExplicitlyCodeRefactoringProvider() { } protected override string Implement_0 => FeaturesResources.Implement_0_explicitly; protected override string Implement_all_interfaces => FeaturesResources.Implement_all_interfaces_explicitly; protected override string Implement => FeaturesResources.Implement_explicitly; // If we already have an explicit name, we can't change this to be explicit. protected override bool CheckExplicitNameAllowsConversion(ExplicitInterfaceSpecifierSyntax? explicitName) => explicitName == null; // If we don't implement any interface members we can't convert this to be explicit. protected override bool CheckMemberCanBeConverted(ISymbol member) => member.ImplicitInterfaceImplementations().Length > 0; protected override async Task UpdateReferencesAsync( Project project, SolutionEditor solutionEditor, ISymbol implMember, INamedTypeSymbol interfaceType, CancellationToken cancellationToken) { var solution = project.Solution; // We don't need to cascade in this search, we're only explicitly looking for direct // calls to our instance member (and not anyone else already calling through the // interface already). // // This can save a lot of extra time spent finding callers, especially for methods with // high fan-out (like IDisposable.Dispose()). var findRefsOptions = FindReferencesSearchOptions.Default.With(cascade: false); var references = await SymbolFinder.FindReferencesAsync( implMember, solution, findRefsOptions, cancellationToken).ConfigureAwait(false); var implReferences = references.FirstOrDefault(); if (implReferences == null) return; var referenceByDocument = implReferences.Locations.GroupBy(loc => loc.Document); foreach (var group in referenceByDocument) { var document = group.Key; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = await solutionEditor.GetDocumentEditorAsync( document.Id, cancellationToken).ConfigureAwait(false); foreach (var refLocation in group) { if (refLocation.IsImplicit) continue; var location = refLocation.Location; if (!location.IsInSource) continue; UpdateLocation( semanticModel, interfaceType, editor, syntaxFacts, location, cancellationToken); } } } private static void UpdateLocation( SemanticModel semanticModel, INamedTypeSymbol interfaceType, SyntaxEditor editor, ISyntaxFactsService syntaxFacts, Location location, CancellationToken cancellationToken) { var identifierName = location.FindNode(getInnermostNodeForTie: true, cancellationToken); if (identifierName == null || !syntaxFacts.IsIdentifierName(identifierName)) return; var node = syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifierName) || syntaxFacts.IsNameOfMemberBindingExpression(identifierName) ? identifierName.Parent : identifierName; RoslynDebug.Assert(node is object); if (syntaxFacts.IsInvocationExpression(node.Parent)) node = node.Parent; var operation = semanticModel.GetOperation(node, cancellationToken); var instance = operation switch { IMemberReferenceOperation memberReference => memberReference.Instance, IInvocationOperation invocation => invocation.Instance, _ => null, }; if (instance == null) return; if (instance.IsImplicit) { if (instance is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind != InstanceReferenceKind.ContainingTypeInstance) { return; } // Accessing the member not off of <dot>. i.e just plain `Goo()`. Replace with // ((IGoo)this).Goo(); var generator = editor.Generator; editor.ReplaceNode( identifierName, generator.MemberAccessExpression( generator.AddParentheses(generator.CastExpression(interfaceType, generator.ThisExpression())), identifierName.WithoutTrivia()).WithTriviaFrom(identifierName)); } else { // Accessing the member like `x.Goo()`. Replace with `((IGoo)x).Goo()` editor.ReplaceNode( instance.Syntax, (current, g) => g.AddParentheses( g.CastExpression(interfaceType, current.WithoutTrivia())).WithTriviaFrom(current)); } } protected override SyntaxNode ChangeImplementation(SyntaxGenerator generator, SyntaxNode decl, ISymbol interfaceMember) => generator.WithExplicitInterfaceImplementations(decl, ImmutableArray.Create(interfaceMember)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ImplementInterface { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly), Shared] internal class CSharpImplementExplicitlyCodeRefactoringProvider : AbstractChangeImplementionCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpImplementExplicitlyCodeRefactoringProvider() { } protected override string Implement_0 => FeaturesResources.Implement_0_explicitly; protected override string Implement_all_interfaces => FeaturesResources.Implement_all_interfaces_explicitly; protected override string Implement => FeaturesResources.Implement_explicitly; // If we already have an explicit name, we can't change this to be explicit. protected override bool CheckExplicitNameAllowsConversion(ExplicitInterfaceSpecifierSyntax? explicitName) => explicitName == null; // If we don't implement any interface members we can't convert this to be explicit. protected override bool CheckMemberCanBeConverted(ISymbol member) => member.ImplicitInterfaceImplementations().Length > 0; protected override async Task UpdateReferencesAsync( Project project, SolutionEditor solutionEditor, ISymbol implMember, INamedTypeSymbol interfaceType, CancellationToken cancellationToken) { var solution = project.Solution; // We don't need to cascade in this search, we're only explicitly looking for direct // calls to our instance member (and not anyone else already calling through the // interface already). // // This can save a lot of extra time spent finding callers, especially for methods with // high fan-out (like IDisposable.Dispose()). var findRefsOptions = FindReferencesSearchOptions.Default.With(cascade: false); var references = await SymbolFinder.FindReferencesAsync( implMember, solution, findRefsOptions, cancellationToken).ConfigureAwait(false); var implReferences = references.FirstOrDefault(); if (implReferences == null) return; var referenceByDocument = implReferences.Locations.GroupBy(loc => loc.Document); foreach (var group in referenceByDocument) { var document = group.Key; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = await solutionEditor.GetDocumentEditorAsync( document.Id, cancellationToken).ConfigureAwait(false); foreach (var refLocation in group) { if (refLocation.IsImplicit) continue; var location = refLocation.Location; if (!location.IsInSource) continue; UpdateLocation( semanticModel, interfaceType, editor, syntaxFacts, location, cancellationToken); } } } private static void UpdateLocation( SemanticModel semanticModel, INamedTypeSymbol interfaceType, SyntaxEditor editor, ISyntaxFactsService syntaxFacts, Location location, CancellationToken cancellationToken) { var identifierName = location.FindNode(getInnermostNodeForTie: true, cancellationToken); if (identifierName == null || !syntaxFacts.IsIdentifierName(identifierName)) return; var node = syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifierName) || syntaxFacts.IsNameOfMemberBindingExpression(identifierName) ? identifierName.Parent : identifierName; RoslynDebug.Assert(node is object); if (syntaxFacts.IsInvocationExpression(node.Parent)) node = node.Parent; var operation = semanticModel.GetOperation(node, cancellationToken); var instance = operation switch { IMemberReferenceOperation memberReference => memberReference.Instance, IInvocationOperation invocation => invocation.Instance, _ => null, }; if (instance == null) return; if (instance.IsImplicit) { if (instance is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind != InstanceReferenceKind.ContainingTypeInstance) { return; } // Accessing the member not off of <dot>. i.e just plain `Goo()`. Replace with // ((IGoo)this).Goo(); var generator = editor.Generator; editor.ReplaceNode( identifierName, generator.MemberAccessExpression( generator.AddParentheses(generator.CastExpression(interfaceType, generator.ThisExpression())), identifierName.WithoutTrivia()).WithTriviaFrom(identifierName)); } else { // Accessing the member like `x.Goo()`. Replace with `((IGoo)x).Goo()` editor.ReplaceNode( instance.Syntax, (current, g) => g.AddParentheses( g.CastExpression(interfaceType, current.WithoutTrivia())).WithTriviaFrom(current)); } } protected override SyntaxNode ChangeImplementation(SyntaxGenerator generator, SyntaxNode decl, ISymbol interfaceMember) => generator.WithExplicitInterfaceImplementations(decl, ImmutableArray.Create(interfaceMember)); } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_BasePatternSwitchLocalRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { /// <summary> /// A common base class for lowering the pattern switch statement and the pattern switch expression. /// </summary> private abstract class BaseSwitchLocalRewriter : DecisionDagRewriter { /// <summary> /// Map from when clause's syntax to the lowered code for the matched pattern. The code for a section /// includes the code to assign to the pattern variables and evaluate the when clause. Since a /// when clause can yield a false value, it can jump back to a label in the lowered decision dag. /// </summary> private readonly PooledDictionary<SyntaxNode, ArrayBuilder<BoundStatement>> _switchArms = PooledDictionary<SyntaxNode, ArrayBuilder<BoundStatement>>.GetInstance(); protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode whenClauseSyntax) { // We need the section syntax to get the section builder from the map. Unfortunately this is a bit awkward SyntaxNode? sectionSyntax = whenClauseSyntax is SwitchLabelSyntax l ? l.Parent : whenClauseSyntax; Debug.Assert(sectionSyntax is { }); bool found = _switchArms.TryGetValue(sectionSyntax, out ArrayBuilder<BoundStatement>? result); if (!found || result == null) throw new InvalidOperationException(); return result; } protected BaseSwitchLocalRewriter( SyntaxNode node, LocalRewriter localRewriter, ImmutableArray<SyntaxNode> arms, bool generateInstrumentation) : base(node, localRewriter, generateInstrumentation) { foreach (var arm in arms) { var armBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // We start each switch block of a switch statement with a hidden sequence point so that // we do not appear to be in the previous switch block when we begin. if (GenerateInstrumentation) armBuilder.Add(_factory.HiddenSequencePoint()); _switchArms.Add(arm, armBuilder); } } protected new void Free() { _switchArms.Free(); base.Free(); } /// <summary> /// Lower the given nodes into _loweredDecisionDag. Should only be called once per instance of this. /// </summary> protected (ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) LowerDecisionDag(BoundDecisionDag decisionDag) { var loweredDag = LowerDecisionDagCore(decisionDag); var switchSections = _switchArms.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.ToImmutableAndFree()); _switchArms.Clear(); return (loweredDag, switchSections); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { /// <summary> /// A common base class for lowering the pattern switch statement and the pattern switch expression. /// </summary> private abstract class BaseSwitchLocalRewriter : DecisionDagRewriter { /// <summary> /// Map from when clause's syntax to the lowered code for the matched pattern. The code for a section /// includes the code to assign to the pattern variables and evaluate the when clause. Since a /// when clause can yield a false value, it can jump back to a label in the lowered decision dag. /// </summary> private readonly PooledDictionary<SyntaxNode, ArrayBuilder<BoundStatement>> _switchArms = PooledDictionary<SyntaxNode, ArrayBuilder<BoundStatement>>.GetInstance(); protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode whenClauseSyntax) { // We need the section syntax to get the section builder from the map. Unfortunately this is a bit awkward SyntaxNode? sectionSyntax = whenClauseSyntax is SwitchLabelSyntax l ? l.Parent : whenClauseSyntax; Debug.Assert(sectionSyntax is { }); bool found = _switchArms.TryGetValue(sectionSyntax, out ArrayBuilder<BoundStatement>? result); if (!found || result == null) throw new InvalidOperationException(); return result; } protected BaseSwitchLocalRewriter( SyntaxNode node, LocalRewriter localRewriter, ImmutableArray<SyntaxNode> arms, bool generateInstrumentation) : base(node, localRewriter, generateInstrumentation) { foreach (var arm in arms) { var armBuilder = ArrayBuilder<BoundStatement>.GetInstance(); // We start each switch block of a switch statement with a hidden sequence point so that // we do not appear to be in the previous switch block when we begin. if (GenerateInstrumentation) armBuilder.Add(_factory.HiddenSequencePoint()); _switchArms.Add(arm, armBuilder); } } protected new void Free() { _switchArms.Free(); base.Free(); } /// <summary> /// Lower the given nodes into _loweredDecisionDag. Should only be called once per instance of this. /// </summary> protected (ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) LowerDecisionDag(BoundDecisionDag decisionDag) { var loweredDag = LowerDecisionDagCore(decisionDag); var switchSections = _switchArms.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.ToImmutableAndFree()); _switchArms.Clear(); return (loweredDag, switchSections); } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.CaptureIdDispenser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal sealed partial class ControlFlowGraphBuilder { internal class CaptureIdDispenser { private int _captureId = -1; public int GetNextId() { return Interlocked.Increment(ref _captureId); } public int GetCurrentId() { return _captureId; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal sealed partial class ControlFlowGraphBuilder { internal class CaptureIdDispenser { private int _captureId = -1; public int GetNextId() { return Interlocked.Increment(ref _captureId); } public int GetCurrentId() { return _captureId; } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.AnalysisData.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Simple data holder for local diagnostics for an analyzer /// </summary> private readonly struct DocumentAnalysisData { public static readonly DocumentAnalysisData Empty = new(VersionStamp.Default, ImmutableArray<DiagnosticData>.Empty); /// <summary> /// Version of the diagnostic data. /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version. /// </summary> public readonly ImmutableArray<DiagnosticData> Items; /// <summary> /// Last set of data we broadcasted to outer world, or <see langword="default"/>. /// </summary> public readonly ImmutableArray<DiagnosticData> OldItems; public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); Version = version; Items = items; OldItems = default; } public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems) : this(version, newItems) { Debug.Assert(!oldItems.IsDefault); OldItems = oldItems; } public DocumentAnalysisData ToPersistData() => new(Version, Items); public bool FromCache { get { return OldItems.IsDefault; } } } /// <summary> /// Data holder for all diagnostics for a project for an analyzer /// </summary> private readonly struct ProjectAnalysisData { /// <summary> /// ProjectId of this data /// </summary> public readonly ProjectId ProjectId; /// <summary> /// Version of the Items /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> Result; /// <summary> /// When present, holds onto last data we broadcasted to outer world. /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? OldResult; public ProjectAnalysisData(ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { ProjectId = projectId; Version = version; Result = result; OldResult = null; } public ProjectAnalysisData( ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult) : this(projectId, version, newResult) { OldResult = oldResult; } public DiagnosticAnalysisResult GetResult(DiagnosticAnalyzer analyzer) => GetResultOrEmpty(Result, analyzer, ProjectId, Version); public static async Task<ProjectAnalysisData> CreateAsync(Project project, IEnumerable<StateSet> stateSets, bool avoidLoadingData, CancellationToken cancellationToken) { VersionStamp? version = null; var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResult>(); foreach (var stateSet in stateSets) { var state = stateSet.GetOrCreateProjectState(project.Id); var result = await state.GetAnalysisDataAsync(project, avoidLoadingData, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(project.Id == result.ProjectId); if (!version.HasValue) { version = result.Version; } else if (version.Value != VersionStamp.Default && version.Value != result.Version) { // if not all version is same, set version as default. // this can happen at the initial data loading or // when document is closed and we put active file state to project state version = VersionStamp.Default; } builder.Add(stateSet.Analyzer, result); } if (!version.HasValue) { // there is no saved data to return. return new ProjectAnalysisData(project.Id, VersionStamp.Default, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } return new ProjectAnalysisData(project.Id, version.Value, builder.ToImmutable()); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Simple data holder for local diagnostics for an analyzer /// </summary> private readonly struct DocumentAnalysisData { public static readonly DocumentAnalysisData Empty = new(VersionStamp.Default, ImmutableArray<DiagnosticData>.Empty); /// <summary> /// Version of the diagnostic data. /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version. /// </summary> public readonly ImmutableArray<DiagnosticData> Items; /// <summary> /// Last set of data we broadcasted to outer world, or <see langword="default"/>. /// </summary> public readonly ImmutableArray<DiagnosticData> OldItems; public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); Version = version; Items = items; OldItems = default; } public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems) : this(version, newItems) { Debug.Assert(!oldItems.IsDefault); OldItems = oldItems; } public DocumentAnalysisData ToPersistData() => new(Version, Items); public bool FromCache { get { return OldItems.IsDefault; } } } /// <summary> /// Data holder for all diagnostics for a project for an analyzer /// </summary> private readonly struct ProjectAnalysisData { /// <summary> /// ProjectId of this data /// </summary> public readonly ProjectId ProjectId; /// <summary> /// Version of the Items /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> Result; /// <summary> /// When present, holds onto last data we broadcasted to outer world. /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? OldResult; public ProjectAnalysisData(ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { ProjectId = projectId; Version = version; Result = result; OldResult = null; } public ProjectAnalysisData( ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult) : this(projectId, version, newResult) { OldResult = oldResult; } public DiagnosticAnalysisResult GetResult(DiagnosticAnalyzer analyzer) => GetResultOrEmpty(Result, analyzer, ProjectId, Version); public static async Task<ProjectAnalysisData> CreateAsync(Project project, IEnumerable<StateSet> stateSets, bool avoidLoadingData, CancellationToken cancellationToken) { VersionStamp? version = null; var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResult>(); foreach (var stateSet in stateSets) { var state = stateSet.GetOrCreateProjectState(project.Id); var result = await state.GetAnalysisDataAsync(project, avoidLoadingData, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(project.Id == result.ProjectId); if (!version.HasValue) { version = result.Version; } else if (version.Value != VersionStamp.Default && version.Value != result.Version) { // if not all version is same, set version as default. // this can happen at the initial data loading or // when document is closed and we put active file state to project state version = VersionStamp.Default; } builder.Add(stateSet.Analyzer, result); } if (!version.HasValue) { // there is no saved data to return. return new ProjectAnalysisData(project.Id, VersionStamp.Default, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } return new ProjectAnalysisData(project.Id, version.Value, builder.ToImmutable()); } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/ProjectSystemReferenceUpdate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal sealed class ProjectSystemReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public ProjectSystemUpdateAction Action { get; } /// <summary> /// Gets the reference to be updated. /// </summary> public ProjectSystemReferenceInfo ReferenceInfo { get; } public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal sealed class ProjectSystemReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public ProjectSystemUpdateAction Action { get; } /// <summary> /// Gets the reference to be updated. /// </summary> public ProjectSystemReferenceInfo ReferenceInfo { get; } public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace { public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_InvalidFolderName1() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }} </Document> </Project> </Workspace>"; await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_InvalidFolderName2() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }} </Document> </Project> </Workspace>"; await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentNoReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace}; class Class1 {{ }} </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C; class Class1 { } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentLocalReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ delegate void D1; interface Class1 {{ void M1(); }} class Class2 : {declaredNamespace}.Class1 {{ {declaredNamespace}.D1 d; void {declaredNamespace}.Class1.M1(){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { D1 d; void Class1.M1() { } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithCrefReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1.M1""/&gt; /// &lt;/summary&gt; public class Class1 {{ public void M1() {{ }} }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1.M1""/&gt; /// &lt;/summary&gt; class RefClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// See <see cref=""global::A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1.M1""/> /// </summary> public class Class1 { public void M1() { } } }"; var expectedSourceReference = @" namespace Foo { using A.B.C; /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1.M1""/> /// </summary> class RefClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithCrefReferencesInVB() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} ''' &lt;summary&gt; ''' See &lt;see cref=""Class1""/&gt; ''' See &lt;see cref=""{declaredNamespace}.Class1""/&gt; ''' &lt;/summary&gt; Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C ''' <summary> ''' See <see cref=""Class1""/> ''' See <see cref=""Class1""/> ''' </summary> Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Class2 c2; private Class3 c3; private Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Foo.Class2 c2; private Foo.Bar.Class3 c3; private Foo.Bar.Baz.Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Foo.Bar.Baz; namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ interface Interface1 {{ void M1(Interface1 c1); }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass : Interface1 {{ void {declaredNamespace}.Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { interface Interface1 { void M1(Interface1 c1); } }"; var expectedSourceReference = @" namespace Foo { using A.B.C; class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c2; }} namespace NS2 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; var expectedSourceReference = @" namespace NS1 { using A.B.C; class Class2 { Class1 c2; } namespace NS2 { class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; using Class1Alias = Foo.Bar.Baz.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using System; using A.B.C; using Class1Alias = A.B.C.Class1; namespace Foo { class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_SingleDocumentNoRef() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; // Comments before declaration. namespace [||]{declaredNamespace} {{ // Comments after opening brace class Class1 {{ }} // Comments before closing brace }} // Comments after declaration. </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using System; // Comments before declaration. // Comments after opening brace class Class1 { } // Comments before closing brace // Comments after declaration. "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ delegate void D1; interface Class1 {{ void M1(); }} class Class2 : {declaredNamespace}.Class1 {{ global::{declaredNamespace}.D1 d; void {declaredNamespace}.Class1.M1() {{ }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { global::D1 d; void Class1.M1() { } } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Foo.Bar.Baz; namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } class Class2 { } "; var expectedSourceReference = @"namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ interface Interface1 {{ void M1(Interface1 c1); }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass : Interface1 {{ void {declaredNamespace}.Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"interface Interface1 { void M1(Interface1 c1); } "; var expectedSourceReference = @" namespace Foo { class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class MyClass {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass {{ Foo.Bar.Baz.MyClass c; }} class MyClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class MyClass { } "; var expectedSourceReference = @" namespace Foo { class RefClass { global::MyClass c; } class MyClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Class2 c2; private Class3 c3; private Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c2; }} namespace NS2 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } "; var expectedSourceReference = @" namespace NS1 { class Class2 { Class1 c2; } namespace NS2 { class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; using Class1Alias = Foo.Bar.Baz.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } class Class2 { } "; var expectedSourceReference = @"using System; using Class1Alias = Class1; namespace Foo { class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; class [||]Class1 {{ }} </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using System; namespace A.B.C { class Class1 { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> delegate void [||]D1; interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { D1 d; void Class1.M1() { } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }} class Class2 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> interface [||]Interface1 {{ void M1(Interface1 c1); }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass : Interface1 {{ void Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { interface Interface1 { void M1(Interface1 c1); } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ private A.Class2 c2; private A.B.Class3 c3; private A.B.C.Class4 c4; }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace A {{ class Class2 {{}} namespace B {{ class Class3 {{}} namespace C {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using System; class Class2 {{ Class1 c2; }} namespace NS2 {{ using System; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; var expectedSourceReference = @" namespace NS1 { using System; using A.B.C; class Class2 { Class1 c2; } namespace NS2 { using System; class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }} class Class2 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Class1Alias = Class1; namespace Foo {{ using System; class RefClass {{ private Class1Alias c1; void M1() {{ Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; using Class1Alias = Class1; namespace Foo { using System; class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Public ReadOnly Property C1 As A.B.C.D.Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @"Public Class VBClass Public ReadOnly Property C1 As A.B.C.Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> public class [||]Class1 {{ }} </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithCredReferences() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// &lt;/summary&gt; class [||]Class1 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// &lt;/summary&gt; class Bar {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// </summary> class Class1 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { /// <summary> /// See <see cref=""Class1""/> /// </summary> class Bar { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public class Class1 { } "; var expectedSourceReference = @"Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class MyClass {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Namespace Foo Public Class VBClass Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass End Class Public Class MyClass End Class End Namespace</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public class MyClass { } "; var expectedSourceReference = @"Namespace Foo Public Class VBClass Public ReadOnly Property C1 As Global.MyClass End Class Public Class MyClass End Class End Namespace"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithCredReferences() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; public class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; class RefClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"/// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> public class Class1 { } "; var expectedSourceReference = @" namespace Foo { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> class RefClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ExtensionMethodInReducedForm() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{defaultNamespace} {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace {defaultNamespace} {{ using System; public class Class1 {{ public bool Bar(Class1 c1) => c1.Foo(); }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@"namespace A.B.C {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}"; var expectedSourceReference = $@" namespace {defaultNamespace} {{ using System; using A.B.C; public class Class1 {{ public bool Bar(Class1 c1) => c1.Foo(); }} }}"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ExternsionMethodInRegularForm() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]A {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1) => Extensions.Foo(c1); }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@"namespace A.B.C {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}"; var expectedSourceReference = $@" using System; using A.B.C; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1) => Extensions.Foo(c1); }} }}"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]A {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} public class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true; }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public static class Extensions { public static bool Foo(this Class1 c1) => true; } public class Class2 { } }"; var expectedSourceReference = @" using System; using A.B.C; namespace A { public class Class1 { public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; namespace [||]{declaredNamespace} {{ public static class Extensions {{ public static bool Foo(this String s) => true; }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public Function Foo(s As string) As Boolean Return s.Foo() End Function End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@" using System; namespace {defaultNamespace} {{ public static class Extensions {{ public static bool Foo(this string s) => true; }} }}"; var expectedSourceReference = $@" Imports {defaultNamespace} Public Class VBClass Public Function Foo(s As string) As Boolean Return s.Foo() End Function End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ enum Enum1 {{ A, B, C }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ Enum1 M1() {{ return {declaredNamespace}.Enum1.A; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { enum Enum1 { A, B, C } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { Enum1 M1() { return Enum1.A; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ enum Enum1 {{ A, B, C }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ Enum1 M1() {{ return {declaredNamespace}.Enum1.A; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"enum Enum1 { A, B, C } "; var expectedSourceReference = @"namespace Foo { class RefClass { Enum1 M1() { return Enum1.A; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ public enum Enum1 {{ A, B, C }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Sub M() Dim x = A.B.C.D.Enum1.A End Sub End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public enum Enum1 { A, B, C } }"; var expectedSourceReference = @"Public Class VBClass Sub M() Dim x = A.B.C.Enum1.A End Sub End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ public enum Enum1 {{ A, B, C }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Sub M() Dim x = A.B.C.D.Enum1.A End Sub End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public enum Enum1 { A, B, C } "; var expectedSourceReference = @"Public Class VBClass Sub M() Dim x = Enum1.A End Sub End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace { public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_InvalidFolderName1() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }} </Document> </Project> </Workspace>"; await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_InvalidFolderName2() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; // No change namespace action because the folder name is not valid identifier var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }} </Document> </Project> </Workspace>"; await TestChangeNamespaceAsync(code, expectedSourceOriginal: null); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentNoReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace}; class Class1 {{ }} </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C; class Class1 { } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_SingleDocumentLocalReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ delegate void D1; interface Class1 {{ void M1(); }} class Class2 : {declaredNamespace}.Class1 {{ {declaredNamespace}.D1 d; void {declaredNamespace}.Class1.M1(){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { D1 d; void Class1.M1() { } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithCrefReference() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1.M1""/&gt; /// &lt;/summary&gt; public class Class1 {{ public void M1() {{ }} }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1""/&gt; /// See &lt;see cref=""global::{declaredNamespace}.Class1.M1""/&gt; /// &lt;/summary&gt; class RefClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// See <see cref=""global::A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1.M1""/> /// </summary> public class Class1 { public void M1() { } } }"; var expectedSourceReference = @" namespace Foo { using A.B.C; /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1""/> /// See <see cref=""global::A.B.C.Class1.M1""/> /// </summary> class RefClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithCrefReferencesInVB() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} ''' &lt;summary&gt; ''' See &lt;see cref=""Class1""/&gt; ''' See &lt;see cref=""{declaredNamespace}.Class1""/&gt; ''' &lt;/summary&gt; Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C ''' <summary> ''' See <see cref=""Class1""/> ''' See <see cref=""Class1""/> ''' </summary> Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Class2 c2; private Class3 c3; private Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Foo.Class2 c2; private Foo.Bar.Class3 c3; private Foo.Bar.Baz.Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Foo.Bar.Baz; namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ interface Interface1 {{ void M1(Interface1 c1); }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass : Interface1 {{ void {declaredNamespace}.Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { interface Interface1 { void M1(Interface1 c1); } }"; var expectedSourceReference = @" namespace Foo { using A.B.C; class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c2; }} namespace NS2 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; var expectedSourceReference = @" namespace NS1 { using A.B.C; class Class2 { Class1 c2; } namespace NS2 { class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; using Class1Alias = Foo.Bar.Baz.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using System; using A.B.C; using Class1Alias = A.B.C.Class1; namespace Foo { class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_SingleDocumentNoRef() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; // Comments before declaration. namespace [||]{declaredNamespace} {{ // Comments after opening brace class Class1 {{ }} // Comments before closing brace }} // Comments after declaration. </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using System; // Comments before declaration. // Comments after opening brace class Class1 { } // Comments before closing brace // Comments after declaration. "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ delegate void D1; interface Class1 {{ void M1(); }} class Class2 : {declaredNamespace}.Class1 {{ global::{declaredNamespace}.D1 d; void {declaredNamespace}.Class1.M1() {{ }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { global::D1 d; void Class1.M1() { } } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Foo.Bar.Baz; namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } class Class2 { } "; var expectedSourceReference = @"namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ interface Interface1 {{ void M1(Interface1 c1); }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass : Interface1 {{ void {declaredNamespace}.Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"interface Interface1 { void M1(Interface1 c1); } "; var expectedSourceReference = @" namespace Foo { class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class MyClass {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; class RefClass {{ Foo.Bar.Baz.MyClass c; }} class MyClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class MyClass { } "; var expectedSourceReference = @" namespace Foo { class RefClass { global::MyClass c; } class MyClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ private Class2 c2; private Class3 c3; private Class4 c4; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class Class2 {{}} namespace Bar {{ class Class3 {{}} namespace Baz {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using Foo; using Foo.Bar; using Foo.Bar.Baz; class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } "; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c2; }} namespace NS2 {{ using Foo.Bar.Baz; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } "; var expectedSourceReference = @" namespace NS1 { class Class2 { Class1 c2; } namespace NS2 { class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ class Class1 {{ }} class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; using Class1Alias = Foo.Bar.Baz.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; void M1() {{ Bar.Baz.Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"class Class1 { } class Class2 { } "; var expectedSourceReference = @"using System; using Class1Alias = Class1; namespace Foo { class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; class [||]Class1 {{ }} </Document> </Project> </Workspace>"; var expectedSourceOriginal = @"using System; namespace A.B.C { class Class1 { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> delegate void [||]D1; interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { delegate void D1; interface Class1 { void M1(); } class Class2 : Class1 { D1 d; void Class1.M1() { } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }} class Class2 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ private Class1 c1; void M1() {{ Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { private Class1 c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> interface [||]Interface1 {{ void M1(Interface1 c1); }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass : Interface1 {{ void Interface1.M1(Interface1 c1){{}} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { interface Interface1 { void M1(Interface1 c1); } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass : Interface1 { void Interface1.M1(Interface1 c1){} } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ private A.Class2 c2; private A.B.Class3 c3; private A.B.C.Class4 c4; }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace A {{ class Class2 {{}} namespace B {{ class Class3 {{}} namespace C {{ class Class4 {{}} }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { private Class2 c2; private Class3 c3; private Class4 c4; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace NS1 {{ using System; class Class2 {{ Class1 c2; }} namespace NS2 {{ using System; class Class2 {{ Class1 c1; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } }"; var expectedSourceReference = @" namespace NS1 { using System; using A.B.C; class Class2 { Class1 c2; } namespace NS2 { using System; class Class2 { Class1 c1; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> class [||]Class1 {{ }} class Class2 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using Class1Alias = Class1; namespace Foo {{ using System; class RefClass {{ private Class1Alias c1; void M1() {{ Class2 c2 = null; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { class Class1 { } class Class2 { } }"; var expectedSourceReference = @" using A.B.C; using Class1Alias = Class1; namespace Foo { using System; class RefClass { private Class1Alias c1; void M1() { Class2 c2 = null; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Public ReadOnly Property C1 As A.B.C.D.Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @"Public Class VBClass Public ReadOnly Property C1 As A.B.C.Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> public class [||]Class1 {{ }} </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public class Class1 { } }"; var expectedSourceReference = @" Imports A.B.C Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeFromGlobalNamespace_WithCredReferences() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// &lt;/summary&gt; class [||]Class1 {{ }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// &lt;/summary&gt; class Bar {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { /// <summary> /// See <see cref=""Class1""/> /// </summary> class Class1 { } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { /// <summary> /// See <see cref=""Class1""/> /// </summary> class Bar { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class Class1 {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public ReadOnly Property C1 As Class1 End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public class Class1 { } "; var expectedSourceReference = @"Public Class VBClass Public ReadOnly Property C1 As Class1 End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ public class MyClass {{ }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Namespace Foo Public Class VBClass Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass End Class Public Class MyClass End Class End Namespace</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public class MyClass { } "; var expectedSourceReference = @"Namespace Foo Public Class VBClass Public ReadOnly Property C1 As Global.MyClass End Class Public Class MyClass End Class End Namespace"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithCredReferences() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{declaredNamespace} {{ /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; public class Class1 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ using {declaredNamespace}; /// &lt;summary&gt; /// See &lt;see cref=""Class1""/&gt; /// See &lt;see cref=""{declaredNamespace}.Class1""/&gt; /// &lt;/summary&gt; class RefClass {{ }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"/// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> public class Class1 { } "; var expectedSourceReference = @" namespace Foo { /// <summary> /// See <see cref=""Class1""/> /// See <see cref=""Class1""/> /// </summary> class RefClass { } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ExtensionMethodInReducedForm() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]{defaultNamespace} {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace {defaultNamespace} {{ using System; public class Class1 {{ public bool Bar(Class1 c1) => c1.Foo(); }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@"namespace A.B.C {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}"; var expectedSourceReference = $@" namespace {defaultNamespace} {{ using System; using A.B.C; public class Class1 {{ public bool Bar(Class1 c1) => c1.Foo(); }} }}"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ExternsionMethodInRegularForm() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]A {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1) => Extensions.Foo(c1); }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@"namespace A.B.C {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} }}"; var expectedSourceReference = $@" using System; using A.B.C; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1) => Extensions.Foo(c1); }} }}"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod() { var defaultNamespace = "A"; var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> namespace [||]A {{ public static class Extensions {{ public static bool Foo(this Class1 c1) => true; }} public class Class2 {{ }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> using System; namespace A {{ public class Class1 {{ public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true; }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public static class Extensions { public static bool Foo(this Class1 c1) => true; } public class Class2 { } }"; var expectedSourceReference = @" using System; using A.B.C; namespace A { public class Class1 { public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true; } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{folder}"" FilePath=""{filePath}""> using System; namespace [||]{declaredNamespace} {{ public static class Extensions {{ public static bool Foo(this String s) => true; }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Imports {declaredNamespace} Public Class VBClass Public Function Foo(s As string) As Boolean Return s.Foo() End Function End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = $@" using System; namespace {defaultNamespace} {{ public static class Extensions {{ public static bool Foo(this string s) => true; }} }}"; var expectedSourceReference = $@" Imports {defaultNamespace} Public Class VBClass Public Function Foo(s As string) As Boolean Return s.Foo() End Function End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument() { var defaultNamespace = "A"; var declaredNamespace = "Foo.Bar.Baz"; var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ enum Enum1 {{ A, B, C }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ Enum1 M1() {{ return {declaredNamespace}.Enum1.A; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { enum Enum1 { A, B, C } }"; var expectedSourceReference = @" using A.B.C; namespace Foo { class RefClass { Enum1 M1() { return Enum1.A; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument() { var defaultNamespace = ""; var declaredNamespace = "Foo.Bar.Baz"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ enum Enum1 {{ A, B, C }} }}</Document> <Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}""> namespace Foo {{ class RefClass {{ Enum1 M1() {{ return {declaredNamespace}.Enum1.A; }} }} }}</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"enum Enum1 { A, B, C } "; var expectedSourceReference = @"namespace Foo { class RefClass { Enum1 M1() { return Enum1.A; } } }"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument() { var defaultNamespace = "A.B.C"; var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ public enum Enum1 {{ A, B, C }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Sub M() Dim x = A.B.C.D.Enum1.A End Sub End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"namespace A.B.C { public enum Enum1 { A, B, C } }"; var expectedSourceReference = @"Public Class VBClass Sub M() Dim x = A.B.C.Enum1.A End Sub End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } [WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)] public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument() { var defaultNamespace = ""; var declaredNamespace = "A.B.C.D"; var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs"); var code = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true""> <Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}""> namespace [||]{declaredNamespace} {{ public enum Enum1 {{ A, B, C }} }}</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> Public Class VBClass Sub M() Dim x = A.B.C.D.Enum1.A End Sub End Class</Document> </Project> </Workspace>"; var expectedSourceOriginal = @"public enum Enum1 { A, B, C } "; var expectedSourceReference = @"Public Class VBClass Sub M() Dim x = Enum1.A End Sub End Class"; await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provides workspace status /// /// this is an work in-progress interface, subject to be changed as we work on prototype. /// /// it can completely removed at the end or new APIs can added and removed as prototype going on /// no one except one in the prototype group should use this interface. /// /// tracking issue - https://github.com/dotnet/roslyn/issues/34415 /// </summary> internal interface IWorkspaceStatusService : IWorkspaceService { /// <summary> /// Indicate that status has changed /// </summary> event EventHandler StatusChanged; /// <summary> /// Wait until workspace is fully loaded /// /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can /// deadlock /// </summary> Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken); /// <summary> /// Indicates whether workspace is fully loaded /// /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can /// deadlock /// </summary> Task<bool> IsFullyLoadedAsync(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; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provides workspace status /// /// this is an work in-progress interface, subject to be changed as we work on prototype. /// /// it can completely removed at the end or new APIs can added and removed as prototype going on /// no one except one in the prototype group should use this interface. /// /// tracking issue - https://github.com/dotnet/roslyn/issues/34415 /// </summary> internal interface IWorkspaceStatusService : IWorkspaceService { /// <summary> /// Indicate that status has changed /// </summary> event EventHandler StatusChanged; /// <summary> /// Wait until workspace is fully loaded /// /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can /// deadlock /// </summary> Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken); /// <summary> /// Indicates whether workspace is fully loaded /// /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can /// deadlock /// </summary> Task<bool> IsFullyLoadedAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Core/Portable/Compilation.EmitStream.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class Compilation { /// <summary> /// Describes the kind of real signing that is being done during Emit. In the case of public signing /// this value will be <see cref="None"/>. /// </summary> internal enum EmitStreamSignKind { None, /// <summary> /// This form of signing occurs in memory using the <see cref="PEBuilder"/> APIs. This is the default /// form of signing and will be used when a strong name key is provided in a file on disk. /// </summary> SignedWithBuilder, /// <summary> /// This form of signing occurs using the <see cref="IClrStrongName"/> COM APIs. This form of signing /// requires the unsigned PE to be written to disk before it can be signed (typically by writing it /// out to the %TEMP% folder). This signing is used when the key in a key container, the signing /// requires a counter signature or customers opted in via the UseLegacyStrongNameProvider feature /// flag. /// </summary> SignedWithFile, } /// <summary> /// This type abstracts away the legacy COM based signing implementation for PE streams. Under the hood /// a temporary file must be created on disk (at the last possible moment), emitted to, signed on disk /// and then copied back to the original <see cref="Stream"/>. Only when legacy signing is enabled though. /// </summary> internal sealed class EmitStream { private readonly EmitStreamProvider _emitStreamProvider; private readonly EmitStreamSignKind _emitStreamSignKind; private readonly StrongNameProvider? _strongNameProvider; private (Stream tempStream, string tempFilePath)? _tempInfo; /// <summary> /// The <see cref="Stream"/> that is being emitted into. This value should _never_ be /// disposed. It is either returned from the <see cref="EmitStreamProvider"/> instance in /// which case it is owned by that. Or it is just an alias for the value that is stored /// in <see cref="_tempInfo"/> in which case it will be disposed from there. /// </summary> private Stream? _stream; internal EmitStream( EmitStreamProvider emitStreamProvider, EmitStreamSignKind emitStreamSignKind, StrongNameProvider? strongNameProvider) { RoslynDebug.Assert(emitStreamProvider != null); RoslynDebug.Assert(strongNameProvider != null || emitStreamSignKind == EmitStreamSignKind.None); _emitStreamProvider = emitStreamProvider; _emitStreamSignKind = emitStreamSignKind; _strongNameProvider = strongNameProvider; } internal Func<Stream?> GetCreateStreamFunc(DiagnosticBag diagnostics) { return () => CreateStream(diagnostics); } internal void Close() { // The _stream value is deliberately excluded from being disposed here. That value is not // owned by this type. _stream = null; if (_tempInfo.HasValue) { var (tempStream, tempFilePath) = _tempInfo.GetValueOrDefault(); _tempInfo = null; try { tempStream.Dispose(); } finally { try { File.Delete(tempFilePath); } catch { // Not much to do if we can't delete from the temp directory } } } } /// <summary> /// Create the stream which should be used for Emit. This should only be called one time. /// </summary> private Stream? CreateStream(DiagnosticBag diagnostics) { RoslynDebug.Assert(_stream == null); RoslynDebug.Assert(diagnostics != null); if (diagnostics.HasAnyErrors()) { return null; } _stream = _emitStreamProvider.GetOrCreateStream(diagnostics); if (_stream == null) { return null; } // If the current strong name provider is the Desktop version, signing can only be done to on-disk files. // If this binary is configured to be signed, create a temp file, output to that // then stream that to the stream that this method was called with. Otherwise output to the // stream that this method was called with. if (_emitStreamSignKind == EmitStreamSignKind.SignedWithFile) { RoslynDebug.Assert(_strongNameProvider != null); Stream tempStream; string tempFilePath; try { var fileSystem = _strongNameProvider.FileSystem; Func<string, Stream> streamConstructor = path => fileSystem.CreateFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); var tempDir = fileSystem.GetTempPath(); tempFilePath = Path.Combine(tempDir, Guid.NewGuid().ToString("N")); tempStream = FileUtilities.CreateFileStreamChecked(streamConstructor, tempFilePath); } catch (IOException e) { throw new Cci.PeWritingException(e); } _tempInfo = (tempStream, tempFilePath); return tempStream; } else { return _stream; } } internal bool Complete(StrongNameKeys strongNameKeys, CommonMessageProvider messageProvider, DiagnosticBag diagnostics) { RoslynDebug.Assert(_stream != null); RoslynDebug.Assert(_emitStreamSignKind != EmitStreamSignKind.SignedWithFile || _tempInfo.HasValue); try { if (_tempInfo.HasValue) { RoslynDebug.Assert(_emitStreamSignKind == EmitStreamSignKind.SignedWithFile); RoslynDebug.Assert(_strongNameProvider is object); var (tempStream, tempFilePath) = _tempInfo.GetValueOrDefault(); try { // Dispose the temp stream to ensure all of the contents are written to // disk. tempStream.Dispose(); _strongNameProvider.SignFile(strongNameKeys, tempFilePath); using (var tempFileStream = new FileStream(tempFilePath, FileMode.Open)) { tempFileStream.CopyTo(_stream); } } catch (DesktopStrongNameProvider.ClrStrongNameMissingException) { diagnostics.Add(StrongNameKeys.GetError(strongNameKeys.KeyFilePath, strongNameKeys.KeyContainer, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider)); return false; } catch (IOException ex) { diagnostics.Add(StrongNameKeys.GetError(strongNameKeys.KeyFilePath, strongNameKeys.KeyContainer, ex.Message, messageProvider)); return false; } } } finally { Close(); } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class Compilation { /// <summary> /// Describes the kind of real signing that is being done during Emit. In the case of public signing /// this value will be <see cref="None"/>. /// </summary> internal enum EmitStreamSignKind { None, /// <summary> /// This form of signing occurs in memory using the <see cref="PEBuilder"/> APIs. This is the default /// form of signing and will be used when a strong name key is provided in a file on disk. /// </summary> SignedWithBuilder, /// <summary> /// This form of signing occurs using the <see cref="IClrStrongName"/> COM APIs. This form of signing /// requires the unsigned PE to be written to disk before it can be signed (typically by writing it /// out to the %TEMP% folder). This signing is used when the key in a key container, the signing /// requires a counter signature or customers opted in via the UseLegacyStrongNameProvider feature /// flag. /// </summary> SignedWithFile, } /// <summary> /// This type abstracts away the legacy COM based signing implementation for PE streams. Under the hood /// a temporary file must be created on disk (at the last possible moment), emitted to, signed on disk /// and then copied back to the original <see cref="Stream"/>. Only when legacy signing is enabled though. /// </summary> internal sealed class EmitStream { private readonly EmitStreamProvider _emitStreamProvider; private readonly EmitStreamSignKind _emitStreamSignKind; private readonly StrongNameProvider? _strongNameProvider; private (Stream tempStream, string tempFilePath)? _tempInfo; /// <summary> /// The <see cref="Stream"/> that is being emitted into. This value should _never_ be /// disposed. It is either returned from the <see cref="EmitStreamProvider"/> instance in /// which case it is owned by that. Or it is just an alias for the value that is stored /// in <see cref="_tempInfo"/> in which case it will be disposed from there. /// </summary> private Stream? _stream; internal EmitStream( EmitStreamProvider emitStreamProvider, EmitStreamSignKind emitStreamSignKind, StrongNameProvider? strongNameProvider) { RoslynDebug.Assert(emitStreamProvider != null); RoslynDebug.Assert(strongNameProvider != null || emitStreamSignKind == EmitStreamSignKind.None); _emitStreamProvider = emitStreamProvider; _emitStreamSignKind = emitStreamSignKind; _strongNameProvider = strongNameProvider; } internal Func<Stream?> GetCreateStreamFunc(DiagnosticBag diagnostics) { return () => CreateStream(diagnostics); } internal void Close() { // The _stream value is deliberately excluded from being disposed here. That value is not // owned by this type. _stream = null; if (_tempInfo.HasValue) { var (tempStream, tempFilePath) = _tempInfo.GetValueOrDefault(); _tempInfo = null; try { tempStream.Dispose(); } finally { try { File.Delete(tempFilePath); } catch { // Not much to do if we can't delete from the temp directory } } } } /// <summary> /// Create the stream which should be used for Emit. This should only be called one time. /// </summary> private Stream? CreateStream(DiagnosticBag diagnostics) { RoslynDebug.Assert(_stream == null); RoslynDebug.Assert(diagnostics != null); if (diagnostics.HasAnyErrors()) { return null; } _stream = _emitStreamProvider.GetOrCreateStream(diagnostics); if (_stream == null) { return null; } // If the current strong name provider is the Desktop version, signing can only be done to on-disk files. // If this binary is configured to be signed, create a temp file, output to that // then stream that to the stream that this method was called with. Otherwise output to the // stream that this method was called with. if (_emitStreamSignKind == EmitStreamSignKind.SignedWithFile) { RoslynDebug.Assert(_strongNameProvider != null); Stream tempStream; string tempFilePath; try { var fileSystem = _strongNameProvider.FileSystem; Func<string, Stream> streamConstructor = path => fileSystem.CreateFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); var tempDir = fileSystem.GetTempPath(); tempFilePath = Path.Combine(tempDir, Guid.NewGuid().ToString("N")); tempStream = FileUtilities.CreateFileStreamChecked(streamConstructor, tempFilePath); } catch (IOException e) { throw new Cci.PeWritingException(e); } _tempInfo = (tempStream, tempFilePath); return tempStream; } else { return _stream; } } internal bool Complete(StrongNameKeys strongNameKeys, CommonMessageProvider messageProvider, DiagnosticBag diagnostics) { RoslynDebug.Assert(_stream != null); RoslynDebug.Assert(_emitStreamSignKind != EmitStreamSignKind.SignedWithFile || _tempInfo.HasValue); try { if (_tempInfo.HasValue) { RoslynDebug.Assert(_emitStreamSignKind == EmitStreamSignKind.SignedWithFile); RoslynDebug.Assert(_strongNameProvider is object); var (tempStream, tempFilePath) = _tempInfo.GetValueOrDefault(); try { // Dispose the temp stream to ensure all of the contents are written to // disk. tempStream.Dispose(); _strongNameProvider.SignFile(strongNameKeys, tempFilePath); using (var tempFileStream = new FileStream(tempFilePath, FileMode.Open)) { tempFileStream.CopyTo(_stream); } } catch (DesktopStrongNameProvider.ClrStrongNameMissingException) { diagnostics.Add(StrongNameKeys.GetError(strongNameKeys.KeyFilePath, strongNameKeys.KeyContainer, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider)); return false; } catch (IOException ex) { diagnostics.Add(StrongNameKeys.GetError(strongNameKeys.KeyFilePath, strongNameKeys.KeyContainer, ex.Message, messageProvider)); return false; } } } finally { Close(); } return true; } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Core/Portable/Symbols/IAssemblySymbol.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a .NET assembly, consisting of one or more modules. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAssemblySymbol : ISymbol { /// <summary> /// True if the assembly contains interactive code. /// </summary> bool IsInteractive { get; } /// <summary> /// Gets the name of this assembly. /// </summary> AssemblyIdentity Identity { get; } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> INamespaceSymbol GlobalNamespace { get; } /// <summary> /// Gets the modules in this assembly. (There must be at least one.) The first one is the main module /// that holds the assembly manifest. /// </summary> IEnumerable<IModuleSymbol> Modules { get; } /// <summary> /// Gets the set of type identifiers from this assembly. /// </summary> ICollection<string> TypeNames { get; } /// <summary> /// Gets the set of namespace names from this assembly. /// </summary> ICollection<string> NamespaceNames { get; } /// <summary> /// Gets a value indicating whether this assembly gives /// <paramref name="toAssembly"/> access to internal symbols</summary> bool GivesAccessTo(IAssemblySymbol toAssembly); /// <summary> /// Lookup a type within the assembly using the canonical CLR metadata name of the type. /// </summary> /// <param name="fullyQualifiedMetadataName">Type name.</param> /// <returns>Symbol for the type or null if type cannot be found or is ambiguous. </returns> INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName); /// <summary> /// Determines if the assembly might contain extension methods. /// If false, the assembly does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// Returns the type symbol for a forwarded type based its canonical CLR metadata name. /// The name should refer to a non-nested type. If type with this name is not forwarded, /// null is returned. /// </summary> INamedTypeSymbol? ResolveForwardedType(string fullyQualifiedMetadataName); /// <summary> /// Returns type symbols for top-level (non-nested) types forwarded by this assembly. /// </summary> ImmutableArray<INamedTypeSymbol> GetForwardedTypes(); /// <summary> /// If this symbol represents a metadata assembly returns the underlying <see cref="AssemblyMetadata"/>. /// /// Otherwise, this returns <see langword="null"/>. /// </summary> AssemblyMetadata? GetMetadata(); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a .NET assembly, consisting of one or more modules. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAssemblySymbol : ISymbol { /// <summary> /// True if the assembly contains interactive code. /// </summary> bool IsInteractive { get; } /// <summary> /// Gets the name of this assembly. /// </summary> AssemblyIdentity Identity { get; } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> INamespaceSymbol GlobalNamespace { get; } /// <summary> /// Gets the modules in this assembly. (There must be at least one.) The first one is the main module /// that holds the assembly manifest. /// </summary> IEnumerable<IModuleSymbol> Modules { get; } /// <summary> /// Gets the set of type identifiers from this assembly. /// </summary> ICollection<string> TypeNames { get; } /// <summary> /// Gets the set of namespace names from this assembly. /// </summary> ICollection<string> NamespaceNames { get; } /// <summary> /// Gets a value indicating whether this assembly gives /// <paramref name="toAssembly"/> access to internal symbols</summary> bool GivesAccessTo(IAssemblySymbol toAssembly); /// <summary> /// Lookup a type within the assembly using the canonical CLR metadata name of the type. /// </summary> /// <param name="fullyQualifiedMetadataName">Type name.</param> /// <returns>Symbol for the type or null if type cannot be found or is ambiguous. </returns> INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName); /// <summary> /// Determines if the assembly might contain extension methods. /// If false, the assembly does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// Returns the type symbol for a forwarded type based its canonical CLR metadata name. /// The name should refer to a non-nested type. If type with this name is not forwarded, /// null is returned. /// </summary> INamedTypeSymbol? ResolveForwardedType(string fullyQualifiedMetadataName); /// <summary> /// Returns type symbols for top-level (non-nested) types forwarded by this assembly. /// </summary> ImmutableArray<INamedTypeSymbol> GetForwardedTypes(); /// <summary> /// If this symbol represents a metadata assembly returns the underlying <see cref="AssemblyMetadata"/>. /// /// Otherwise, this returns <see langword="null"/>. /// </summary> AssemblyMetadata? GetMetadata(); } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Tools/BuildBoss/ProjectCheckerUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; namespace BuildBoss { internal sealed class ProjectCheckerUtil : ICheckerUtil { private readonly ProjectData _data; private readonly ProjectUtil _projectUtil; private readonly Dictionary<ProjectKey, ProjectData> _solutionMap; private readonly bool _isPrimarySolution; internal ProjectFileType ProjectType => _data.ProjectFileType; internal string ProjectFilePath => _data.FilePath; internal ProjectCheckerUtil(ProjectData data, Dictionary<ProjectKey, ProjectData> solutionMap, bool isPrimarySolution) { _data = data; _projectUtil = data.ProjectUtil; _solutionMap = solutionMap; _isPrimarySolution = isPrimarySolution; } public bool Check(TextWriter textWriter) { var allGood = true; if (ProjectType == ProjectFileType.CSharp || ProjectType == ProjectFileType.Basic) { if (!_projectUtil.IsNewSdk) { textWriter.WriteLine($"Project must new .NET SDK based"); allGood = false; } // Properties that aren't related to build but instead artifacts of Visual Studio. allGood &= CheckForProperty(textWriter, "RestorePackages"); allGood &= CheckForProperty(textWriter, "SolutionDir"); allGood &= CheckForProperty(textWriter, "FileAlignment"); allGood &= CheckForProperty(textWriter, "FileUpgradeFlags"); allGood &= CheckForProperty(textWriter, "UpgradeBackupLocation"); allGood &= CheckForProperty(textWriter, "OldToolsVersion"); allGood &= CheckForProperty(textWriter, "SchemaVersion"); // Centrally controlled properties allGood &= CheckForProperty(textWriter, "Configuration"); allGood &= CheckForProperty(textWriter, "CheckForOverflowUnderflow"); allGood &= CheckForProperty(textWriter, "RemoveIntegerChecks"); allGood &= CheckForProperty(textWriter, "Deterministic"); allGood &= CheckForProperty(textWriter, "HighEntropyVA"); allGood &= CheckForProperty(textWriter, "DocumentationFile"); // Items which are not necessary anymore in the new SDK allGood &= CheckForProperty(textWriter, "ProjectGuid"); allGood &= CheckForProperty(textWriter, "ProjectTypeGuids"); allGood &= CheckForProperty(textWriter, "TargetFrameworkProfile"); allGood &= CheckTargetFrameworks(textWriter); allGood &= CheckProjectReferences(textWriter); allGood &= CheckPackageReferences(textWriter); if (_isPrimarySolution) { allGood &= CheckInternalsVisibleTo(textWriter); } allGood &= CheckDeploymentSettings(textWriter); } else if (ProjectType == ProjectFileType.Tool) { allGood &= CheckPackageReferences(textWriter); } return allGood; } private bool CheckForProperty(TextWriter textWriter, string propertyName) { foreach (var element in _projectUtil.GetAllPropertyGroupElements()) { if (element.Name.LocalName == propertyName) { textWriter.WriteLine($"\tDo not use {propertyName}"); return false; } } return true; } private bool CheckProjectReferences(TextWriter textWriter) { var allGood = true; var declaredEntryList = _projectUtil.GetDeclaredProjectReferences(); var declaredList = declaredEntryList.Select(x => x.ProjectKey).ToList(); allGood &= CheckProjectReferencesComplete(textWriter, declaredList); allGood &= CheckUnitTestReferenceRestriction(textWriter, declaredList); allGood &= CheckNoGuidsOnProjectReferences(textWriter, declaredEntryList); return allGood; } private bool CheckNoGuidsOnProjectReferences(TextWriter textWriter, List<ProjectReferenceEntry> entryList) { var allGood = true; foreach (var entry in entryList) { if (entry.Project != null) { textWriter.WriteLine($"Project reference for {entry.ProjectKey.FileName} should not have a GUID"); allGood = false; } } return allGood; } private bool CheckPackageReferences(TextWriter textWriter) { var allGood = true; foreach (var packageRef in _projectUtil.GetPackageReferences()) { var allowedPackageVersons = GetAllowedPackageReferenceVersions(packageRef).ToList(); if (!allowedPackageVersons.Contains(packageRef.Version)) { textWriter.WriteLine($"PackageReference {packageRef.Name} has incorrect version {packageRef.Version}"); textWriter.WriteLine($"Allowed values are " + string.Join(" or", allowedPackageVersons)); allGood = false; } } return allGood; } private IEnumerable<string> GetAllowedPackageReferenceVersions(PackageReference packageReference) { // If this is a generator project, if it has a reference to Microsoft.CodeAnalysis.Common, that means it's // a source generator. In that case, we require the version of the API being built against to match the toolset // version, so that way the source generator can actually be loaded by the toolset. We don't apply this rule to // any other project, as any other project having a reason to reference a version of Roslyn via a PackageReference // probably doesn't fall under this rule. if (ProjectFilePath.Contains("CompilerGeneratorTools") && packageReference.Name == "Microsoft.CodeAnalysis.Common") { yield return "$(SourceGeneratorMicrosoftCodeAnalysisVersion)"; } else { var name = packageReference.Name.Replace(".", "").Replace("-", ""); yield return $"$({name}Version)"; yield return $"$({name}FixedVersion)"; } } private bool CheckInternalsVisibleTo(TextWriter textWriter) { var allGood = true; foreach (var internalsVisibleTo in _projectUtil.GetInternalsVisibleTo()) { if (string.Equals(internalsVisibleTo.LoadsWithinVisualStudio, "false", StringComparison.OrdinalIgnoreCase)) { // IVTs explicitly declared with LoadsWithinVisualStudio="false" are allowed continue; } if (_projectUtil.Key.FileName.StartsWith("Microsoft.CodeAnalysis.ExternalAccess.")) { // External access layer may have external IVTs continue; } if (!string.IsNullOrEmpty(internalsVisibleTo.WorkItem)) { if (!Uri.TryCreate(internalsVisibleTo.WorkItem, UriKind.Absolute, out _)) { textWriter.WriteLine($"InternalsVisibleTo for external assembly '{internalsVisibleTo.TargetAssembly}' does not have a valid URI specified for {nameof(InternalsVisibleTo.WorkItem)}."); allGood = false; } // A work item is tracking elimination of this IVT continue; } var builtByThisRepository = _solutionMap.Values.Any(projectData => GetAssemblyName(projectData) == internalsVisibleTo.TargetAssembly); if (!builtByThisRepository) { textWriter.WriteLine($"InternalsVisibleTo not allowed for external assembly '{internalsVisibleTo.TargetAssembly}' that may load within Visual Studio."); allGood = false; } } return allGood; // Local functions static string GetAssemblyName(ProjectData projectData) { return projectData.ProjectUtil.FindSingleProperty("AssemblyName")?.Value.Trim() ?? Path.GetFileNameWithoutExtension(projectData.FileName); } } private bool CheckDeploymentSettings(TextWriter textWriter) { var allGood = CheckForProperty(textWriter, "CopyNuGetImplementations"); allGood &= CheckForProperty(textWriter, "UseCommonOutputDirectory"); return allGood; } /// <summary> /// It's important that every reference be included in the solution. MSBuild does not necessarily /// apply all configuration entries to projects which are compiled via referenes but not included /// in the solution. /// </summary> private bool CheckProjectReferencesComplete(TextWriter textWriter, IEnumerable<ProjectKey> declaredReferences) { var allGood = true; foreach (var key in declaredReferences) { if (!_solutionMap.ContainsKey(key)) { textWriter.WriteLine($"Project reference {key.FileName} is not included in the solution"); allGood = false; } } return allGood; } /// <summary> /// Unit test projects should not reference each other. In order for unit tests to be run / F5 they must be /// modeled as deployment projects. Having Unit Tests reference each other hurts that because it ends up /// putting two copies of the unit test DLL into the UnitTest folder: /// /// 1. UnitTests\Current\TheUnitTest\TheUnitTest.dll /// 2. UnitTests\Current\TheOtherTests\ /// TheUnitTests.dll /// TheOtherTests.dll /// /// This is problematic as all of our tools do directory based searches for unit test DLLs. Hence they end up /// getting counted twice. /// /// Consideration was given to fixing up all of the tools but it felt like fighting against the grain. Pretty /// much every repo has this practice. /// </summary> private bool CheckUnitTestReferenceRestriction(TextWriter textWriter, IEnumerable<ProjectKey> declaredReferences) { if (!_data.IsTestProject) { return true; } var allGood = true; foreach (var key in declaredReferences) { if (!_solutionMap.TryGetValue(key, out var projectData)) { continue; } if (projectData.ProjectUtil.IsTestProject) { textWriter.WriteLine($"Cannot reference {key.FileName} as it is another unit test project"); allGood = false; } } return allGood; } private bool CheckTargetFrameworks(TextWriter textWriter) { if (!_data.IsUnitTestProject) { return true; } var allGood = true; foreach (var targetFramework in _projectUtil.GetAllTargetFrameworks()) { switch (targetFramework) { case "net20": case "net472": case "netcoreapp3.1": case "net5.0": continue; } textWriter.WriteLine($"TargetFramework {targetFramework} is not supported in this build"); allGood = false; } return allGood; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; namespace BuildBoss { internal sealed class ProjectCheckerUtil : ICheckerUtil { private readonly ProjectData _data; private readonly ProjectUtil _projectUtil; private readonly Dictionary<ProjectKey, ProjectData> _solutionMap; private readonly bool _isPrimarySolution; internal ProjectFileType ProjectType => _data.ProjectFileType; internal string ProjectFilePath => _data.FilePath; internal ProjectCheckerUtil(ProjectData data, Dictionary<ProjectKey, ProjectData> solutionMap, bool isPrimarySolution) { _data = data; _projectUtil = data.ProjectUtil; _solutionMap = solutionMap; _isPrimarySolution = isPrimarySolution; } public bool Check(TextWriter textWriter) { var allGood = true; if (ProjectType == ProjectFileType.CSharp || ProjectType == ProjectFileType.Basic) { if (!_projectUtil.IsNewSdk) { textWriter.WriteLine($"Project must new .NET SDK based"); allGood = false; } // Properties that aren't related to build but instead artifacts of Visual Studio. allGood &= CheckForProperty(textWriter, "RestorePackages"); allGood &= CheckForProperty(textWriter, "SolutionDir"); allGood &= CheckForProperty(textWriter, "FileAlignment"); allGood &= CheckForProperty(textWriter, "FileUpgradeFlags"); allGood &= CheckForProperty(textWriter, "UpgradeBackupLocation"); allGood &= CheckForProperty(textWriter, "OldToolsVersion"); allGood &= CheckForProperty(textWriter, "SchemaVersion"); // Centrally controlled properties allGood &= CheckForProperty(textWriter, "Configuration"); allGood &= CheckForProperty(textWriter, "CheckForOverflowUnderflow"); allGood &= CheckForProperty(textWriter, "RemoveIntegerChecks"); allGood &= CheckForProperty(textWriter, "Deterministic"); allGood &= CheckForProperty(textWriter, "HighEntropyVA"); allGood &= CheckForProperty(textWriter, "DocumentationFile"); // Items which are not necessary anymore in the new SDK allGood &= CheckForProperty(textWriter, "ProjectGuid"); allGood &= CheckForProperty(textWriter, "ProjectTypeGuids"); allGood &= CheckForProperty(textWriter, "TargetFrameworkProfile"); allGood &= CheckTargetFrameworks(textWriter); allGood &= CheckProjectReferences(textWriter); allGood &= CheckPackageReferences(textWriter); if (_isPrimarySolution) { allGood &= CheckInternalsVisibleTo(textWriter); } allGood &= CheckDeploymentSettings(textWriter); } else if (ProjectType == ProjectFileType.Tool) { allGood &= CheckPackageReferences(textWriter); } return allGood; } private bool CheckForProperty(TextWriter textWriter, string propertyName) { foreach (var element in _projectUtil.GetAllPropertyGroupElements()) { if (element.Name.LocalName == propertyName) { textWriter.WriteLine($"\tDo not use {propertyName}"); return false; } } return true; } private bool CheckProjectReferences(TextWriter textWriter) { var allGood = true; var declaredEntryList = _projectUtil.GetDeclaredProjectReferences(); var declaredList = declaredEntryList.Select(x => x.ProjectKey).ToList(); allGood &= CheckProjectReferencesComplete(textWriter, declaredList); allGood &= CheckUnitTestReferenceRestriction(textWriter, declaredList); allGood &= CheckNoGuidsOnProjectReferences(textWriter, declaredEntryList); return allGood; } private bool CheckNoGuidsOnProjectReferences(TextWriter textWriter, List<ProjectReferenceEntry> entryList) { var allGood = true; foreach (var entry in entryList) { if (entry.Project != null) { textWriter.WriteLine($"Project reference for {entry.ProjectKey.FileName} should not have a GUID"); allGood = false; } } return allGood; } private bool CheckPackageReferences(TextWriter textWriter) { var allGood = true; foreach (var packageRef in _projectUtil.GetPackageReferences()) { var allowedPackageVersons = GetAllowedPackageReferenceVersions(packageRef).ToList(); if (!allowedPackageVersons.Contains(packageRef.Version)) { textWriter.WriteLine($"PackageReference {packageRef.Name} has incorrect version {packageRef.Version}"); textWriter.WriteLine($"Allowed values are " + string.Join(" or", allowedPackageVersons)); allGood = false; } } return allGood; } private IEnumerable<string> GetAllowedPackageReferenceVersions(PackageReference packageReference) { // If this is a generator project, if it has a reference to Microsoft.CodeAnalysis.Common, that means it's // a source generator. In that case, we require the version of the API being built against to match the toolset // version, so that way the source generator can actually be loaded by the toolset. We don't apply this rule to // any other project, as any other project having a reason to reference a version of Roslyn via a PackageReference // probably doesn't fall under this rule. if (ProjectFilePath.Contains("CompilerGeneratorTools") && packageReference.Name == "Microsoft.CodeAnalysis.Common") { yield return "$(SourceGeneratorMicrosoftCodeAnalysisVersion)"; } else { var name = packageReference.Name.Replace(".", "").Replace("-", ""); yield return $"$({name}Version)"; yield return $"$({name}FixedVersion)"; } } private bool CheckInternalsVisibleTo(TextWriter textWriter) { var allGood = true; foreach (var internalsVisibleTo in _projectUtil.GetInternalsVisibleTo()) { if (string.Equals(internalsVisibleTo.LoadsWithinVisualStudio, "false", StringComparison.OrdinalIgnoreCase)) { // IVTs explicitly declared with LoadsWithinVisualStudio="false" are allowed continue; } if (_projectUtil.Key.FileName.StartsWith("Microsoft.CodeAnalysis.ExternalAccess.")) { // External access layer may have external IVTs continue; } if (!string.IsNullOrEmpty(internalsVisibleTo.WorkItem)) { if (!Uri.TryCreate(internalsVisibleTo.WorkItem, UriKind.Absolute, out _)) { textWriter.WriteLine($"InternalsVisibleTo for external assembly '{internalsVisibleTo.TargetAssembly}' does not have a valid URI specified for {nameof(InternalsVisibleTo.WorkItem)}."); allGood = false; } // A work item is tracking elimination of this IVT continue; } var builtByThisRepository = _solutionMap.Values.Any(projectData => GetAssemblyName(projectData) == internalsVisibleTo.TargetAssembly); if (!builtByThisRepository) { textWriter.WriteLine($"InternalsVisibleTo not allowed for external assembly '{internalsVisibleTo.TargetAssembly}' that may load within Visual Studio."); allGood = false; } } return allGood; // Local functions static string GetAssemblyName(ProjectData projectData) { return projectData.ProjectUtil.FindSingleProperty("AssemblyName")?.Value.Trim() ?? Path.GetFileNameWithoutExtension(projectData.FileName); } } private bool CheckDeploymentSettings(TextWriter textWriter) { var allGood = CheckForProperty(textWriter, "CopyNuGetImplementations"); allGood &= CheckForProperty(textWriter, "UseCommonOutputDirectory"); return allGood; } /// <summary> /// It's important that every reference be included in the solution. MSBuild does not necessarily /// apply all configuration entries to projects which are compiled via referenes but not included /// in the solution. /// </summary> private bool CheckProjectReferencesComplete(TextWriter textWriter, IEnumerable<ProjectKey> declaredReferences) { var allGood = true; foreach (var key in declaredReferences) { if (!_solutionMap.ContainsKey(key)) { textWriter.WriteLine($"Project reference {key.FileName} is not included in the solution"); allGood = false; } } return allGood; } /// <summary> /// Unit test projects should not reference each other. In order for unit tests to be run / F5 they must be /// modeled as deployment projects. Having Unit Tests reference each other hurts that because it ends up /// putting two copies of the unit test DLL into the UnitTest folder: /// /// 1. UnitTests\Current\TheUnitTest\TheUnitTest.dll /// 2. UnitTests\Current\TheOtherTests\ /// TheUnitTests.dll /// TheOtherTests.dll /// /// This is problematic as all of our tools do directory based searches for unit test DLLs. Hence they end up /// getting counted twice. /// /// Consideration was given to fixing up all of the tools but it felt like fighting against the grain. Pretty /// much every repo has this practice. /// </summary> private bool CheckUnitTestReferenceRestriction(TextWriter textWriter, IEnumerable<ProjectKey> declaredReferences) { if (!_data.IsTestProject) { return true; } var allGood = true; foreach (var key in declaredReferences) { if (!_solutionMap.TryGetValue(key, out var projectData)) { continue; } if (projectData.ProjectUtil.IsTestProject) { textWriter.WriteLine($"Cannot reference {key.FileName} as it is another unit test project"); allGood = false; } } return allGood; } private bool CheckTargetFrameworks(TextWriter textWriter) { if (!_data.IsUnitTestProject) { return true; } var allGood = true; foreach (var targetFramework in _projectUtil.GetAllTargetFrameworks()) { switch (targetFramework) { case "net20": case "net472": case "netcoreapp3.1": case "net5.0": continue; } textWriter.WriteLine($"TargetFramework {targetFramework} is not supported in this build"); allGood = false; } return allGood; } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Portable/Parser/QuickScanner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class Lexer { // Maximum size of tokens/trivia that we cache and use in quick scanner. // From what I see in our own codebase, tokens longer then 40-50 chars are // not very common. // So it seems reasonable to limit the sizes to some round number like 42. internal const int MaxCachedTokenSize = 42; private enum QuickScanState : byte { Initial, FollowingWhite, FollowingCR, Ident, Number, Punctuation, Dot, CompoundPunctStart, DoneAfterNext, // we are relying on Bad state immediately following Done // to be able to detect exiting conditions in one "state >= Done" test. // And we are also relying on this to be the last item in the enum. Done, Bad = Done + 1 } private enum CharFlags : byte { White, // simple whitespace (space/tab) CR, // carriage return LF, // line feed Letter, // letter Digit, // digit 0-9 Punct, // some simple punctuation (parens, braces, comma, equals, question) Dot, // dot is different from other punctuation when followed by a digit (Ex: .9 ) CompoundPunctStart, // may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) Slash, // / Complex, // complex - causes scanning to abort EndOfFile, // legal type character (except !, which is contextually dictionary lookup } // PERF: Use byte instead of QuickScanState so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[,] s_stateTransitions = new byte[,] { // Initial { (byte)QuickScanState.Initial, // White (byte)QuickScanState.Initial, // CR (byte)QuickScanState.Initial, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Punctuation, // Punct (byte)QuickScanState.Dot, // Dot (byte)QuickScanState.CompoundPunctStart, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Bad, // EndOfFile }, // Following White { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Following CR { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Identifier { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Ident, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Number { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Bad, // Letter (might be 'e' or 'x' or suffix) (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (Number is followed by a dot - too complex for us to handle here). (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Dot { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (DotDot range token, exit so that we handle it in subsequent scanning code) (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Compound Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Bad, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Bad, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Done after next { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.Done, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, }; private SyntaxToken QuickScanSyntaxToken() { this.Start(); var state = QuickScanState.Initial; int i = TextWindow.Offset; int n = TextWindow.CharacterWindowCount; n = Math.Min(n, i + MaxCachedTokenSize); int hashCode = Hash.FnvOffsetBias; //localize frequently accessed fields var charWindow = TextWindow.CharacterWindow; var charPropLength = s_charProperties.Length; for (; i < n; i++) { char c = charWindow[i]; int uc = unchecked((int)c); var flags = uc < charPropLength ? (CharFlags)s_charProperties[uc] : CharFlags.Complex; state = (QuickScanState)s_stateTransitions[(int)state, (int)flags]; // NOTE: that Bad > Done and it is the only state like that // as a result, we will exit the loop on either Bad or Done. // the assert below will validate that these are the only states on which we exit // Also note that we must exit on Done or Bad // since the state machine does not have transitions for these states // and will promptly fail if we do not exit. if (state >= QuickScanState.Done) { goto exitWhile; } hashCode = unchecked((hashCode ^ uc) * Hash.FnvPrime); } state = QuickScanState.Bad; // ran out of characters in window exitWhile: TextWindow.AdvanceChar(i - TextWindow.Offset); Debug.Assert(state == QuickScanState.Bad || state == QuickScanState.Done, "can only exit with Bad or Done"); if (state == QuickScanState.Done) { // this is a good token! var token = _cache.LookupToken( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, i - TextWindow.LexemeRelativeStart, hashCode, _createQuickTokenFunction); return token; } else { TextWindow.Reset(TextWindow.LexemeStartPosition); return null; } } private readonly Func<SyntaxToken> _createQuickTokenFunction; private SyntaxToken CreateQuickToken() { #if DEBUG var quickWidth = TextWindow.Width; #endif TextWindow.Reset(TextWindow.LexemeStartPosition); var token = this.LexSyntaxToken(); #if DEBUG Debug.Assert(quickWidth == token.FullWidth); #endif return token; } // The following table classifies the first 0x180 Unicode characters. // # is marked complex as it may start directives. // PERF: Use byte instead of CharFlags so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[] s_charProperties = new[] { // 0 .. 31 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.White, // TAB (byte)CharFlags.LF, // LF (byte)CharFlags.White, // VT (byte)CharFlags.White, // FF (byte)CharFlags.CR, // CR (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 32 .. 63 (byte)CharFlags.White, // SPC (byte)CharFlags.CompoundPunctStart, // ! (byte)CharFlags.Complex, // " (byte)CharFlags.Complex, // # (byte)CharFlags.Complex, // $ (byte)CharFlags.CompoundPunctStart, // % (byte)CharFlags.CompoundPunctStart, // & (byte)CharFlags.Complex, // ' (byte)CharFlags.Punct, // ( (byte)CharFlags.Punct, // ) (byte)CharFlags.CompoundPunctStart, // * (byte)CharFlags.CompoundPunctStart, // + (byte)CharFlags.Punct, // , (byte)CharFlags.CompoundPunctStart, // - (byte)CharFlags.Dot, // . (byte)CharFlags.Slash, // / (byte)CharFlags.Digit, // 0 (byte)CharFlags.Digit, // 1 (byte)CharFlags.Digit, // 2 (byte)CharFlags.Digit, // 3 (byte)CharFlags.Digit, // 4 (byte)CharFlags.Digit, // 5 (byte)CharFlags.Digit, // 6 (byte)CharFlags.Digit, // 7 (byte)CharFlags.Digit, // 8 (byte)CharFlags.Digit, // 9 (byte)CharFlags.CompoundPunctStart, // : (byte)CharFlags.Punct, // ; (byte)CharFlags.CompoundPunctStart, // < (byte)CharFlags.CompoundPunctStart, // = (byte)CharFlags.CompoundPunctStart, // > (byte)CharFlags.CompoundPunctStart, // ? // 64 .. 95 (byte)CharFlags.Complex, // @ (byte)CharFlags.Letter, // A (byte)CharFlags.Letter, // B (byte)CharFlags.Letter, // C (byte)CharFlags.Letter, // D (byte)CharFlags.Letter, // E (byte)CharFlags.Letter, // F (byte)CharFlags.Letter, // G (byte)CharFlags.Letter, // H (byte)CharFlags.Letter, // I (byte)CharFlags.Letter, // J (byte)CharFlags.Letter, // K (byte)CharFlags.Letter, // L (byte)CharFlags.Letter, // M (byte)CharFlags.Letter, // N (byte)CharFlags.Letter, // O (byte)CharFlags.Letter, // P (byte)CharFlags.Letter, // Q (byte)CharFlags.Letter, // R (byte)CharFlags.Letter, // S (byte)CharFlags.Letter, // T (byte)CharFlags.Letter, // U (byte)CharFlags.Letter, // V (byte)CharFlags.Letter, // W (byte)CharFlags.Letter, // X (byte)CharFlags.Letter, // Y (byte)CharFlags.Letter, // Z (byte)CharFlags.Punct, // [ (byte)CharFlags.Complex, // \ (byte)CharFlags.Punct, // ] (byte)CharFlags.CompoundPunctStart, // ^ (byte)CharFlags.Letter, // _ // 96 .. 127 (byte)CharFlags.Complex, // ` (byte)CharFlags.Letter, // a (byte)CharFlags.Letter, // b (byte)CharFlags.Letter, // c (byte)CharFlags.Letter, // d (byte)CharFlags.Letter, // e (byte)CharFlags.Letter, // f (byte)CharFlags.Letter, // g (byte)CharFlags.Letter, // h (byte)CharFlags.Letter, // i (byte)CharFlags.Letter, // j (byte)CharFlags.Letter, // k (byte)CharFlags.Letter, // l (byte)CharFlags.Letter, // m (byte)CharFlags.Letter, // n (byte)CharFlags.Letter, // o (byte)CharFlags.Letter, // p (byte)CharFlags.Letter, // q (byte)CharFlags.Letter, // r (byte)CharFlags.Letter, // s (byte)CharFlags.Letter, // t (byte)CharFlags.Letter, // u (byte)CharFlags.Letter, // v (byte)CharFlags.Letter, // w (byte)CharFlags.Letter, // x (byte)CharFlags.Letter, // y (byte)CharFlags.Letter, // z (byte)CharFlags.Punct, // { (byte)CharFlags.CompoundPunctStart, // | (byte)CharFlags.Punct, // } (byte)CharFlags.CompoundPunctStart, // ~ (byte)CharFlags.Complex, // 128 .. 159 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 160 .. 191 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 192 .. (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class Lexer { // Maximum size of tokens/trivia that we cache and use in quick scanner. // From what I see in our own codebase, tokens longer then 40-50 chars are // not very common. // So it seems reasonable to limit the sizes to some round number like 42. internal const int MaxCachedTokenSize = 42; private enum QuickScanState : byte { Initial, FollowingWhite, FollowingCR, Ident, Number, Punctuation, Dot, CompoundPunctStart, DoneAfterNext, // we are relying on Bad state immediately following Done // to be able to detect exiting conditions in one "state >= Done" test. // And we are also relying on this to be the last item in the enum. Done, Bad = Done + 1 } private enum CharFlags : byte { White, // simple whitespace (space/tab) CR, // carriage return LF, // line feed Letter, // letter Digit, // digit 0-9 Punct, // some simple punctuation (parens, braces, comma, equals, question) Dot, // dot is different from other punctuation when followed by a digit (Ex: .9 ) CompoundPunctStart, // may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) Slash, // / Complex, // complex - causes scanning to abort EndOfFile, // legal type character (except !, which is contextually dictionary lookup } // PERF: Use byte instead of QuickScanState so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[,] s_stateTransitions = new byte[,] { // Initial { (byte)QuickScanState.Initial, // White (byte)QuickScanState.Initial, // CR (byte)QuickScanState.Initial, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Punctuation, // Punct (byte)QuickScanState.Dot, // Dot (byte)QuickScanState.CompoundPunctStart, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Bad, // EndOfFile }, // Following White { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Following CR { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Identifier { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Ident, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Number { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Bad, // Letter (might be 'e' or 'x' or suffix) (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (Number is followed by a dot - too complex for us to handle here). (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Dot { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (DotDot range token, exit so that we handle it in subsequent scanning code) (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Compound Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Bad, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Bad, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Done after next { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.Done, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, }; private SyntaxToken QuickScanSyntaxToken() { this.Start(); var state = QuickScanState.Initial; int i = TextWindow.Offset; int n = TextWindow.CharacterWindowCount; n = Math.Min(n, i + MaxCachedTokenSize); int hashCode = Hash.FnvOffsetBias; //localize frequently accessed fields var charWindow = TextWindow.CharacterWindow; var charPropLength = s_charProperties.Length; for (; i < n; i++) { char c = charWindow[i]; int uc = unchecked((int)c); var flags = uc < charPropLength ? (CharFlags)s_charProperties[uc] : CharFlags.Complex; state = (QuickScanState)s_stateTransitions[(int)state, (int)flags]; // NOTE: that Bad > Done and it is the only state like that // as a result, we will exit the loop on either Bad or Done. // the assert below will validate that these are the only states on which we exit // Also note that we must exit on Done or Bad // since the state machine does not have transitions for these states // and will promptly fail if we do not exit. if (state >= QuickScanState.Done) { goto exitWhile; } hashCode = unchecked((hashCode ^ uc) * Hash.FnvPrime); } state = QuickScanState.Bad; // ran out of characters in window exitWhile: TextWindow.AdvanceChar(i - TextWindow.Offset); Debug.Assert(state == QuickScanState.Bad || state == QuickScanState.Done, "can only exit with Bad or Done"); if (state == QuickScanState.Done) { // this is a good token! var token = _cache.LookupToken( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, i - TextWindow.LexemeRelativeStart, hashCode, _createQuickTokenFunction); return token; } else { TextWindow.Reset(TextWindow.LexemeStartPosition); return null; } } private readonly Func<SyntaxToken> _createQuickTokenFunction; private SyntaxToken CreateQuickToken() { #if DEBUG var quickWidth = TextWindow.Width; #endif TextWindow.Reset(TextWindow.LexemeStartPosition); var token = this.LexSyntaxToken(); #if DEBUG Debug.Assert(quickWidth == token.FullWidth); #endif return token; } // The following table classifies the first 0x180 Unicode characters. // # is marked complex as it may start directives. // PERF: Use byte instead of CharFlags so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[] s_charProperties = new[] { // 0 .. 31 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.White, // TAB (byte)CharFlags.LF, // LF (byte)CharFlags.White, // VT (byte)CharFlags.White, // FF (byte)CharFlags.CR, // CR (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 32 .. 63 (byte)CharFlags.White, // SPC (byte)CharFlags.CompoundPunctStart, // ! (byte)CharFlags.Complex, // " (byte)CharFlags.Complex, // # (byte)CharFlags.Complex, // $ (byte)CharFlags.CompoundPunctStart, // % (byte)CharFlags.CompoundPunctStart, // & (byte)CharFlags.Complex, // ' (byte)CharFlags.Punct, // ( (byte)CharFlags.Punct, // ) (byte)CharFlags.CompoundPunctStart, // * (byte)CharFlags.CompoundPunctStart, // + (byte)CharFlags.Punct, // , (byte)CharFlags.CompoundPunctStart, // - (byte)CharFlags.Dot, // . (byte)CharFlags.Slash, // / (byte)CharFlags.Digit, // 0 (byte)CharFlags.Digit, // 1 (byte)CharFlags.Digit, // 2 (byte)CharFlags.Digit, // 3 (byte)CharFlags.Digit, // 4 (byte)CharFlags.Digit, // 5 (byte)CharFlags.Digit, // 6 (byte)CharFlags.Digit, // 7 (byte)CharFlags.Digit, // 8 (byte)CharFlags.Digit, // 9 (byte)CharFlags.CompoundPunctStart, // : (byte)CharFlags.Punct, // ; (byte)CharFlags.CompoundPunctStart, // < (byte)CharFlags.CompoundPunctStart, // = (byte)CharFlags.CompoundPunctStart, // > (byte)CharFlags.CompoundPunctStart, // ? // 64 .. 95 (byte)CharFlags.Complex, // @ (byte)CharFlags.Letter, // A (byte)CharFlags.Letter, // B (byte)CharFlags.Letter, // C (byte)CharFlags.Letter, // D (byte)CharFlags.Letter, // E (byte)CharFlags.Letter, // F (byte)CharFlags.Letter, // G (byte)CharFlags.Letter, // H (byte)CharFlags.Letter, // I (byte)CharFlags.Letter, // J (byte)CharFlags.Letter, // K (byte)CharFlags.Letter, // L (byte)CharFlags.Letter, // M (byte)CharFlags.Letter, // N (byte)CharFlags.Letter, // O (byte)CharFlags.Letter, // P (byte)CharFlags.Letter, // Q (byte)CharFlags.Letter, // R (byte)CharFlags.Letter, // S (byte)CharFlags.Letter, // T (byte)CharFlags.Letter, // U (byte)CharFlags.Letter, // V (byte)CharFlags.Letter, // W (byte)CharFlags.Letter, // X (byte)CharFlags.Letter, // Y (byte)CharFlags.Letter, // Z (byte)CharFlags.Punct, // [ (byte)CharFlags.Complex, // \ (byte)CharFlags.Punct, // ] (byte)CharFlags.CompoundPunctStart, // ^ (byte)CharFlags.Letter, // _ // 96 .. 127 (byte)CharFlags.Complex, // ` (byte)CharFlags.Letter, // a (byte)CharFlags.Letter, // b (byte)CharFlags.Letter, // c (byte)CharFlags.Letter, // d (byte)CharFlags.Letter, // e (byte)CharFlags.Letter, // f (byte)CharFlags.Letter, // g (byte)CharFlags.Letter, // h (byte)CharFlags.Letter, // i (byte)CharFlags.Letter, // j (byte)CharFlags.Letter, // k (byte)CharFlags.Letter, // l (byte)CharFlags.Letter, // m (byte)CharFlags.Letter, // n (byte)CharFlags.Letter, // o (byte)CharFlags.Letter, // p (byte)CharFlags.Letter, // q (byte)CharFlags.Letter, // r (byte)CharFlags.Letter, // s (byte)CharFlags.Letter, // t (byte)CharFlags.Letter, // u (byte)CharFlags.Letter, // v (byte)CharFlags.Letter, // w (byte)CharFlags.Letter, // x (byte)CharFlags.Letter, // y (byte)CharFlags.Letter, // z (byte)CharFlags.Punct, // { (byte)CharFlags.CompoundPunctStart, // | (byte)CharFlags.Punct, // } (byte)CharFlags.CompoundPunctStart, // ~ (byte)CharFlags.Complex, // 128 .. 159 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 160 .. 191 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 192 .. (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter }; } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.MemoryMappedInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageServiceFactory { /// <summary> /// Our own abstraction on top of memory map file so that we can have shared views over mmf files. /// Otherwise, each view has minimum size of 64K due to requirement forced by windows. /// /// most of our view will have short lifetime, but there are cases where view might live a bit longer such as /// metadata dll shadow copy. shared view will help those cases. /// </summary> /// <remarks> /// <para>Instances of this class should be disposed when they are no longer needed. After disposing this /// instance, it should no longer be used. However, streams obtained through <see cref="CreateReadableStream"/> /// or <see cref="CreateWritableStream"/> will not be invalidated until they are disposed independently (which /// may occur before or after the <see cref="MemoryMappedInfo"/> is disposed.</para> /// /// <para>This class and its nested types have familiar APIs and predictable behavior when used in other code, /// but are non-trivial to work on. The implementations of <see cref="IDisposable"/> adhere to the best /// practices described in /// <see href="http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/">DG /// Update: Dispose, Finalization, and Resource Management</see>. Additional notes regarding operating system /// behavior leveraged for efficiency are given in comments.</para> /// </remarks> internal sealed class MemoryMappedInfo : IDisposable { /// <summary> /// The memory mapped file. /// </summary> /// <remarks> /// <para>It is possible for the file to be disposed prior to the view and/or the streams which use it. /// However, the operating system does not actually close the views which are in use until the file handles /// are closed as well, even if the file is disposed first.</para> /// </remarks> private readonly ReferenceCountedDisposable<MemoryMappedFile> _memoryMappedFile; /// <summary> /// A weak reference to a read-only view for the memory mapped file. /// </summary> /// <remarks> /// <para>This holds a weak counted reference to current <see cref="MemoryMappedViewAccessor"/>, which /// allows additional accessors for the same address space to be obtained up until the point when no /// external code is using it. When the memory is no longer being used by any /// <see cref="SharedReadableStream"/> objects, the view of the memory mapped file is unmapped, making the /// process address space it previously claimed available for other purposes. If/when it is needed again, a /// new view is created.</para> /// /// <para>This view is read-only, so it is only used by <see cref="CreateReadableStream"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference _weakReadAccessor; public MemoryMappedInfo(ReferenceCountedDisposable<MemoryMappedFile> memoryMappedFile, string name, long offset, long size) { _memoryMappedFile = memoryMappedFile; Name = name; Offset = offset; Size = size; } public MemoryMappedInfo(string name, long offset, long size) : this(new ReferenceCountedDisposable<MemoryMappedFile>(MemoryMappedFile.OpenExisting(name)), name, offset, size) { } /// <summary> /// The name of the memory mapped file. /// </summary> public string Name { get; } /// <summary> /// The offset into the memory mapped file of the region described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Offset { get; } /// <summary> /// The size of the region of the memory mapped file described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Size { get; } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will not increase VM. /// </summary> public Stream CreateReadableStream() { // Note: TryAddReference behaves according to its documentation even if the target object has been // disposed. If it returns non-null, then the object will not be disposed before the returned // reference is disposed (see comments on _memoryMappedFile and TryAddReference). var streamAccessor = _weakReadAccessor.TryAddReference(); if (streamAccessor == null) { var rawAccessor = RunWithCompactingGCFallback(info => info._memoryMappedFile.Target.CreateViewAccessor(info.Offset, info.Size, MemoryMappedFileAccess.Read), this); streamAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>(rawAccessor); _weakReadAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference(streamAccessor); } Debug.Assert(streamAccessor.Target.CanRead); return new SharedReadableStream(streamAccessor, Size); } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will increase VM. /// </summary> public Stream CreateWritableStream() { return RunWithCompactingGCFallback(info => info._memoryMappedFile.Target.CreateViewStream(info.Offset, info.Size, MemoryMappedFileAccess.Write), this); } /// <summary> /// Run a function which may fail with an <see cref="IOException"/> if not enough memory is available to /// satisfy the request. In this case, a full compacting GC pass is forced and the function is attempted /// again. /// </summary> /// <remarks> /// <para><see cref="MemoryMappedFile.CreateViewAccessor(long, long, MemoryMappedFileAccess)"/> and /// <see cref="MemoryMappedFile.CreateViewStream(long, long, MemoryMappedFileAccess)"/> will use a native /// memory map, which can't trigger a GC. In this case, we'd otherwise crash with OOM, so we don't care /// about creating a UI delay with a full forced compacting GC. If it crashes the second try, it means we're /// legitimately out of resources.</para> /// </remarks> /// <typeparam name="TArg">The type of argument to pass to the callback.</typeparam> /// <typeparam name="T">The type returned by the function.</typeparam> /// <param name="function">The function to execute.</param> /// <param name="argument">The argument to pass to the function.</param> /// <returns>The value returned by <paramref name="function"/>.</returns> private static T RunWithCompactingGCFallback<TArg, T>(Func<TArg, T> function, TArg argument) { try { return function(argument); } catch (IOException) { ForceCompactingGC(); return function(argument); } } private static void ForceCompactingGC() { // repeated GC.Collect / WaitForPendingFinalizers till memory freed delta is super small, ignore the return value GC.GetTotalMemory(forceFullCollection: true); // compact the LOH GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } public void Dispose() { // See remarks on field for relation between _memoryMappedFile and the views/streams. There is no // need to write _weakReadAccessor here since lifetime of the target is not owned by this instance. _memoryMappedFile.Dispose(); } private sealed unsafe class SharedReadableStream : Stream, ISupportDirectMemoryAccess { private readonly ReferenceCountedDisposable<MemoryMappedViewAccessor> _accessor; private byte* _start; private byte* _current; private readonly byte* _end; public SharedReadableStream(ReferenceCountedDisposable<MemoryMappedViewAccessor> accessor, long length) { _accessor = accessor; _current = _start = (byte*)_accessor.Target.SafeMemoryMappedViewHandle.DangerousGetHandle() + _accessor.Target.PointerOffset; _end = checked(_start + length); } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => _end - _start; public override long Position { get { return _current - _start; } set { var target = _start + value; if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(value)); } _current = target; } } public override int ReadByte() { // PERF: Keeping this as simple as possible since it's on the hot path if (_current >= _end) { return -1; } return *_current++; } public override int Read(byte[] buffer, int offset, int count) { if (_current >= _end) { return 0; } var adjustedCount = Math.Min(count, (int)(_end - _current)); Marshal.Copy((IntPtr)_current, buffer, offset, adjustedCount); _current += adjustedCount; return adjustedCount; } public override long Seek(long offset, SeekOrigin origin) { byte* target; try { target = origin switch { SeekOrigin.Begin => checked(_start + offset), SeekOrigin.Current => checked(_current + offset), SeekOrigin.End => checked(_end + offset), _ => throw new ArgumentOutOfRangeException(nameof(origin)), }; } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(offset)); } _current = target; return _current - _start; } public override void Flush() => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _accessor.Dispose(); } _start = null; } /// <summary> /// Get underlying native memory directly. /// </summary> public IntPtr GetPointer() => (IntPtr)_start; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal partial class TemporaryStorageServiceFactory { /// <summary> /// Our own abstraction on top of memory map file so that we can have shared views over mmf files. /// Otherwise, each view has minimum size of 64K due to requirement forced by windows. /// /// most of our view will have short lifetime, but there are cases where view might live a bit longer such as /// metadata dll shadow copy. shared view will help those cases. /// </summary> /// <remarks> /// <para>Instances of this class should be disposed when they are no longer needed. After disposing this /// instance, it should no longer be used. However, streams obtained through <see cref="CreateReadableStream"/> /// or <see cref="CreateWritableStream"/> will not be invalidated until they are disposed independently (which /// may occur before or after the <see cref="MemoryMappedInfo"/> is disposed.</para> /// /// <para>This class and its nested types have familiar APIs and predictable behavior when used in other code, /// but are non-trivial to work on. The implementations of <see cref="IDisposable"/> adhere to the best /// practices described in /// <see href="http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/">DG /// Update: Dispose, Finalization, and Resource Management</see>. Additional notes regarding operating system /// behavior leveraged for efficiency are given in comments.</para> /// </remarks> internal sealed class MemoryMappedInfo : IDisposable { /// <summary> /// The memory mapped file. /// </summary> /// <remarks> /// <para>It is possible for the file to be disposed prior to the view and/or the streams which use it. /// However, the operating system does not actually close the views which are in use until the file handles /// are closed as well, even if the file is disposed first.</para> /// </remarks> private readonly ReferenceCountedDisposable<MemoryMappedFile> _memoryMappedFile; /// <summary> /// A weak reference to a read-only view for the memory mapped file. /// </summary> /// <remarks> /// <para>This holds a weak counted reference to current <see cref="MemoryMappedViewAccessor"/>, which /// allows additional accessors for the same address space to be obtained up until the point when no /// external code is using it. When the memory is no longer being used by any /// <see cref="SharedReadableStream"/> objects, the view of the memory mapped file is unmapped, making the /// process address space it previously claimed available for other purposes. If/when it is needed again, a /// new view is created.</para> /// /// <para>This view is read-only, so it is only used by <see cref="CreateReadableStream"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference _weakReadAccessor; public MemoryMappedInfo(ReferenceCountedDisposable<MemoryMappedFile> memoryMappedFile, string name, long offset, long size) { _memoryMappedFile = memoryMappedFile; Name = name; Offset = offset; Size = size; } public MemoryMappedInfo(string name, long offset, long size) : this(new ReferenceCountedDisposable<MemoryMappedFile>(MemoryMappedFile.OpenExisting(name)), name, offset, size) { } /// <summary> /// The name of the memory mapped file. /// </summary> public string Name { get; } /// <summary> /// The offset into the memory mapped file of the region described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Offset { get; } /// <summary> /// The size of the region of the memory mapped file described by the current /// <see cref="MemoryMappedInfo"/>. /// </summary> public long Size { get; } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will not increase VM. /// </summary> public Stream CreateReadableStream() { // Note: TryAddReference behaves according to its documentation even if the target object has been // disposed. If it returns non-null, then the object will not be disposed before the returned // reference is disposed (see comments on _memoryMappedFile and TryAddReference). var streamAccessor = _weakReadAccessor.TryAddReference(); if (streamAccessor == null) { var rawAccessor = RunWithCompactingGCFallback(info => info._memoryMappedFile.Target.CreateViewAccessor(info.Offset, info.Size, MemoryMappedFileAccess.Read), this); streamAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>(rawAccessor); _weakReadAccessor = new ReferenceCountedDisposable<MemoryMappedViewAccessor>.WeakReference(streamAccessor); } Debug.Assert(streamAccessor.Target.CanRead); return new SharedReadableStream(streamAccessor, Size); } /// <summary> /// Caller is responsible for disposing the returned stream. /// multiple call of this will increase VM. /// </summary> public Stream CreateWritableStream() { return RunWithCompactingGCFallback(info => info._memoryMappedFile.Target.CreateViewStream(info.Offset, info.Size, MemoryMappedFileAccess.Write), this); } /// <summary> /// Run a function which may fail with an <see cref="IOException"/> if not enough memory is available to /// satisfy the request. In this case, a full compacting GC pass is forced and the function is attempted /// again. /// </summary> /// <remarks> /// <para><see cref="MemoryMappedFile.CreateViewAccessor(long, long, MemoryMappedFileAccess)"/> and /// <see cref="MemoryMappedFile.CreateViewStream(long, long, MemoryMappedFileAccess)"/> will use a native /// memory map, which can't trigger a GC. In this case, we'd otherwise crash with OOM, so we don't care /// about creating a UI delay with a full forced compacting GC. If it crashes the second try, it means we're /// legitimately out of resources.</para> /// </remarks> /// <typeparam name="TArg">The type of argument to pass to the callback.</typeparam> /// <typeparam name="T">The type returned by the function.</typeparam> /// <param name="function">The function to execute.</param> /// <param name="argument">The argument to pass to the function.</param> /// <returns>The value returned by <paramref name="function"/>.</returns> private static T RunWithCompactingGCFallback<TArg, T>(Func<TArg, T> function, TArg argument) { try { return function(argument); } catch (IOException) { ForceCompactingGC(); return function(argument); } } private static void ForceCompactingGC() { // repeated GC.Collect / WaitForPendingFinalizers till memory freed delta is super small, ignore the return value GC.GetTotalMemory(forceFullCollection: true); // compact the LOH GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } public void Dispose() { // See remarks on field for relation between _memoryMappedFile and the views/streams. There is no // need to write _weakReadAccessor here since lifetime of the target is not owned by this instance. _memoryMappedFile.Dispose(); } private sealed unsafe class SharedReadableStream : Stream, ISupportDirectMemoryAccess { private readonly ReferenceCountedDisposable<MemoryMappedViewAccessor> _accessor; private byte* _start; private byte* _current; private readonly byte* _end; public SharedReadableStream(ReferenceCountedDisposable<MemoryMappedViewAccessor> accessor, long length) { _accessor = accessor; _current = _start = (byte*)_accessor.Target.SafeMemoryMappedViewHandle.DangerousGetHandle() + _accessor.Target.PointerOffset; _end = checked(_start + length); } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => _end - _start; public override long Position { get { return _current - _start; } set { var target = _start + value; if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(value)); } _current = target; } } public override int ReadByte() { // PERF: Keeping this as simple as possible since it's on the hot path if (_current >= _end) { return -1; } return *_current++; } public override int Read(byte[] buffer, int offset, int count) { if (_current >= _end) { return 0; } var adjustedCount = Math.Min(count, (int)(_end - _current)); Marshal.Copy((IntPtr)_current, buffer, offset, adjustedCount); _current += adjustedCount; return adjustedCount; } public override long Seek(long offset, SeekOrigin origin) { byte* target; try { target = origin switch { SeekOrigin.Begin => checked(_start + offset), SeekOrigin.Current => checked(_current + offset), SeekOrigin.End => checked(_end + offset), _ => throw new ArgumentOutOfRangeException(nameof(origin)), }; } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < _start || target >= _end) { throw new ArgumentOutOfRangeException(nameof(offset)); } _current = target; return _current - _start; } public override void Flush() => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _accessor.Dispose(); } _start = null; } /// <summary> /// Get underlying native memory directly. /// </summary> public IntPtr GetPointer() => (IntPtr)_start; } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Test/Semantic/Semantics/InheritanceBindingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Areas: interface mapping, virtual/abstract/override methods, /// virtual properties, sealed members, new members, accessibility /// of inherited methods, etc. /// </summary> public class InheritanceBindingTests : CompilingTestBase { [Fact] public void TestModifiersOnExplicitImpl() { var text = @" interface IGoo { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); void Method8(); void Method9(); void Method10(); void Method11(); void Method12(); void Method13(); void Method14(); } abstract partial class AbstractGoo : IGoo { abstract void IGoo.Method1() { } virtual void IGoo.Method2() { } override void IGoo.Method3() { } sealed void IGoo.Method4() { } new void IGoo.Method5() { } public void IGoo.Method6() { } protected void IGoo.Method7() { } internal void IGoo.Method8() { } protected internal void IGoo.Method9() { } //roslyn considers 'protected internal' one modifier (two in dev10) private void IGoo.Method10() { } extern void IGoo.Method11(); //not an error (in dev10 or roslyn) static void IGoo.Method12() { } partial void IGoo.Method13(); private protected void IGoo.Method14() { } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (22,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract void IGoo.Method1() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method1").WithArguments("abstract").WithLocation(22, 24), // (23,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual void IGoo.Method2() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method2").WithArguments("virtual").WithLocation(23, 23), // (24,24): error CS0106: The modifier 'override' is not valid for this item // override void IGoo.Method3() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method3").WithArguments("override").WithLocation(24, 24), // (26,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed void IGoo.Method4() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method4").WithArguments("sealed").WithLocation(26, 22), // (28,19): error CS0106: The modifier 'new' is not valid for this item // new void IGoo.Method5() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method5").WithArguments("new").WithLocation(28, 19), // (30,22): error CS0106: The modifier 'public' is not valid for this item // public void IGoo.Method6() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method6").WithArguments("public").WithLocation(30, 22), // (31,25): error CS0106: The modifier 'protected' is not valid for this item // protected void IGoo.Method7() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method7").WithArguments("protected").WithLocation(31, 25), // (32,24): error CS0106: The modifier 'internal' is not valid for this item // internal void IGoo.Method8() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method8").WithArguments("internal").WithLocation(32, 24), // (33,34): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal void IGoo.Method9() { } //roslyn considers 'protected internal' one modifier (two in dev10) Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method9").WithArguments("protected internal").WithLocation(33, 34), // (34,23): error CS0106: The modifier 'private' is not valid for this item // private void IGoo.Method10() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method10").WithArguments("private").WithLocation(34, 23), // (37,22): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void IGoo.Method12() { } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Method12").WithArguments("static", "9.0", "preview").WithLocation(37, 22), // (40,33): error CS0106: The modifier 'private protected' is not valid for this item // private protected void IGoo.Method14() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method14").WithArguments("private protected").WithLocation(40, 33), // (37,22): error CS0539: 'AbstractGoo.Method12()' in explicit interface declaration is not found among members of the interface that can be implemented // static void IGoo.Method12() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method12").WithArguments("AbstractGoo.Method12()").WithLocation(37, 22), // (38,23): error CS0754: A partial method may not explicitly implement an interface method // partial void IGoo.Method13(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "Method13").WithLocation(38, 23), // (20,38): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Method12()' // abstract partial class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Method12()").WithLocation(20, 38), // (36,22): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.Method11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void IGoo.Method11(); //not an error (in dev10 or roslyn) Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Method11").WithArguments("AbstractGoo.IGoo.Method11()").WithLocation(36, 22) ); } [Fact] public void TestModifiersOnExplicitPropertyImpl() { var text = @" interface IGoo { int Property1 { set; } int Property2 { set; } int Property3 { set; } int Property4 { set; } int Property5 { set; } int Property6 { set; } int Property7 { set; } int Property8 { set; } int Property9 { set; } int Property10 { set; } int Property11 { set; } int Property12 { set; } } abstract class AbstractGoo : IGoo { abstract int IGoo.Property1 { set { } } virtual int IGoo.Property2 { set { } } override int IGoo.Property3 { set { } } sealed int IGoo.Property4 { set { } } new int IGoo.Property5 { set { } } public int IGoo.Property6 { set { } } protected int IGoo.Property7 { set { } } internal int IGoo.Property8 { set { } } protected internal int IGoo.Property9 { set { } } //roslyn considers 'protected internal' one modifier (two in dev10) private int IGoo.Property10 { set { } } extern int IGoo.Property11 { set; } //not an error (in dev10 or roslyn) static int IGoo.Property12 { set { } } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (20,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property1").WithArguments("abstract"), // (21,22): error CS0106: The modifier 'virtual' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property2").WithArguments("virtual"), // (22,23): error CS0106: The modifier 'override' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property3").WithArguments("override"), // (24,21): error CS0106: The modifier 'sealed' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property4").WithArguments("sealed"), // (26,18): error CS0106: The modifier 'new' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property5").WithArguments("new"), // (28,21): error CS0106: The modifier 'public' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property6").WithArguments("public"), // (29,24): error CS0106: The modifier 'protected' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property7").WithArguments("protected"), // (30,23): error CS0106: The modifier 'internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property8").WithArguments("internal"), // (31,33): error CS0106: The modifier 'protected internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property9").WithArguments("protected internal"), // (32,22): error CS0106: The modifier 'private' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property10").WithArguments("private"), // (35,21): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int IGoo.Property12 { set { } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Property12").WithArguments("static", "9.0", "preview").WithLocation(35, 21), // (35,21): error CS0539: 'AbstractGoo.Property12' in explicit interface declaration is not found among members of the interface that can be implemented // static int IGoo.Property12 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property12").WithArguments("AbstractGoo.Property12").WithLocation(35, 21), // (18,30): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Property12' // abstract class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Property12").WithLocation(18, 30), // (34,34): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.Property11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("AbstractGoo.IGoo.Property11.set")); } [Fact] public void TestModifiersOnExplicitIndexerImpl() { var text = @" interface IGoo { int this[int x1, int x2, int x3, int x4] { set; } int this[int x1, int x2, int x3, long x4] { set; } int this[int x1, int x2, long x3, int x4] { set; } int this[int x1, int x2, long x3, long x4] { set; } int this[int x1, long x2, int x3, int x4] { set; } int this[int x1, long x2, int x3, long x4] { set; } int this[int x1, long x2, long x3, int x4] { set; } int this[int x1, long x2, long x3, long x4] { set; } int this[long x1, int x2, int x3, int x4] { set; } int this[long x1, int x2, int x3, long x4] { set; } int this[long x1, int x2, long x3, int x4] { set; } int this[long x1, int x2, long x3, long x4] { set; } } abstract class AbstractGoo : IGoo { abstract int IGoo.this[int x1, int x2, int x3, int x4] { set { } } virtual int IGoo.this[int x1, int x2, int x3, long x4] { set { } } override int IGoo.this[int x1, int x2, long x3, int x4] { set { } } sealed int IGoo.this[int x1, int x2, long x3, long x4] { set { } } new int IGoo.this[int x1, long x2, int x3, int x4] { set { } } public int IGoo.this[int x1, long x2, int x3, long x4] { set { } } protected int IGoo.this[int x1, long x2, long x3, int x4] { set { } } internal int IGoo.this[int x1, long x2, long x3, long x4] { set { } } protected internal int IGoo.this[long x1, int x2, int x3, int x4] { set { } } //roslyn considers 'protected internal' one modifier (two in dev10) private int IGoo.this[long x1, int x2, int x3, long x4] { set { } } extern int IGoo.this[long x1, int x2, long x3, int x4] { set; } //not an error (in dev10 or roslyn) static int IGoo.this[long x1, int x2, long x3, long x4] { set { } } }"; CreateCompilation(text).VerifyDiagnostics( // (20,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract"), // (21,22): error CS0106: The modifier 'virtual' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual"), // (22,23): error CS0106: The modifier 'override' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override"), // (24,21): error CS0106: The modifier 'sealed' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed"), // (26,18): error CS0106: The modifier 'new' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("new"), // (28,21): error CS0106: The modifier 'public' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public"), // (29,24): error CS0106: The modifier 'protected' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected"), // (30,23): error CS0106: The modifier 'internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("internal"), // (31,33): error CS0106: The modifier 'protected internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected internal"), // (32,22): error CS0106: The modifier 'private' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private"), // (35,21): error CS0106: The modifier 'static' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static"), // (34,62): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.this[long, int, long, int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("AbstractGoo.IGoo.this[long, int, long, int].set")); } [Fact, WorkItem(542158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542158")] public void TestModifiersOnExplicitEventImpl() { var text = @" interface IGoo { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; event System.Action Event7; event System.Action Event8; event System.Action Event9; event System.Action Event10; event System.Action Event11; event System.Action Event12; } abstract class AbstractGoo : IGoo { abstract event System.Action IGoo.Event1 { add { } remove { } } virtual event System.Action IGoo.Event2 { add { } remove { } } override event System.Action IGoo.Event3 { add { } remove { } } sealed event System.Action IGoo.Event4 { add { } remove { } } new event System.Action IGoo.Event5 { add { } remove { } } public event System.Action IGoo.Event6 { add { } remove { } } protected event System.Action IGoo.Event7 { add { } remove { } } internal event System.Action IGoo.Event8 { add { } remove { } } protected internal event System.Action IGoo.Event9 { add { } remove { } } //roslyn considers 'protected internal' one modifier (two in dev10) private event System.Action IGoo.Event10 { add { } remove { } } extern event System.Action IGoo.Event11 { add { } remove { } } static event System.Action IGoo.Event12 { add { } remove { } } }"; // It seems Dev11 doesn't report ERR_ExternHasBody errors for Event11 accessors // if there are other explicitly implemented members with erroneous modifiers other than extern and abstract. // If the other errors are fixed ERR_ExternHasBody is reported. // We report all errors at once since they are unrelated, not cascading. CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (20,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action IGoo.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event1").WithArguments("abstract"), // (21,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual event System.Action IGoo.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event2").WithArguments("virtual"), // (22,39): error CS0106: The modifier 'override' is not valid for this item // override event System.Action IGoo.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event3").WithArguments("override"), // (24,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed event System.Action IGoo.Event4 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event4").WithArguments("sealed"), // (26,34): error CS0106: The modifier 'new' is not valid for this item // new event System.Action IGoo.Event5 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event5").WithArguments("new"), // (28,37): error CS0106: The modifier 'public' is not valid for this item // public event System.Action IGoo.Event6 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event6").WithArguments("public"), // (29,40): error CS0106: The modifier 'protected' is not valid for this item // protected event System.Action IGoo.Event7 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event7").WithArguments("protected"), // (30,39): error CS0106: The modifier 'internal' is not valid for this item // internal event System.Action IGoo.Event8 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event8").WithArguments("internal"), // (31,49): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal event System.Action IGoo.Event9 { add { } remove { } } //roslyn considers 'protected internal' one modifier (two in dev10) Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event9").WithArguments("protected internal"), // (32,38): error CS0106: The modifier 'private' is not valid for this item // private event System.Action IGoo.Event10 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event10").WithArguments("private"), // (34,47): error CS0179: 'AbstractGoo.IGoo.Event11.add' cannot be extern and declare a body // extern event System.Action IGoo.Event11 { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("AbstractGoo.IGoo.Event11.add"), // (34,55): error CS0179: 'AbstractGoo.IGoo.Event11.remove' cannot be extern and declare a body // extern event System.Action IGoo.Event11 { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("AbstractGoo.IGoo.Event11.remove"), // (35,37): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action IGoo.Event12 { add { } remove { } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Event12").WithArguments("static", "9.0", "preview").WithLocation(35, 37), // (35,37): error CS0539: 'AbstractGoo.Event12' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action IGoo.Event12 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event12").WithArguments("AbstractGoo.Event12").WithLocation(35, 37), // (18,30): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Event12' // abstract class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Event12").WithLocation(18, 30) ); } [Fact] // can't bind to events public void TestInvokeExplicitMemberDirectly() { // Tests: // Sanity check – it should be an error to invoke a member by its fully qualified explicit implementation name var text = @" interface Interface { void Method<T>(); void Method(int i, long j); long Property { set; } event System.Action Event; } class Class : Interface { void Interface.Method(int i, long j) { Interface.Method(1, 2); } void Interface.Method<T>() { Interface.Method<T>(); } long Interface.Property { set { } } event System.Action Interface.Event { add { } remove { } } void Test() { Interface.Property = 2; Interface.Event += null; Class c = new Class(); c.Interface.Method(1, 2); c.Interface.Method<string>(); c.Interface.Property = 2; c.Interface.Event += null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Method(int, long)' // Interface.Method(1, 2); Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Method").WithArguments("Interface.Method(int, long)").WithLocation(13, 9), // (18,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Method<T>()' // Interface.Method<T>(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Method<T>").WithArguments("Interface.Method<T>()").WithLocation(18, 9), // (27,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Property' // Interface.Property = 2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Property").WithArguments("Interface.Property").WithLocation(27, 9), // (28,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Event' // Interface.Event += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Event").WithArguments("Interface.Event").WithLocation(28, 9), // (31,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Method(1, 2); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(31, 11), // (32,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Method<string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(32, 11), // (33,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Property = 2; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(33, 11), // (34,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Event += null; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(34, 11)); } [Fact] public void TestHidesAbstractMethod() { var text = @" abstract class AbstractGoo { public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); } abstract class Goo : AbstractGoo { public void Method1() { } public abstract void Method2(); public virtual void Method3() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractProperty() { var text = @" abstract class AbstractGoo { public abstract long Property1 { set; } public abstract long Property2 { set; } public abstract long Property3 { set; } } abstract class Goo : AbstractGoo { public long Property1 { set { } } public abstract long Property2 { set; } public virtual long Property3 { set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractIndexer() { var text = @" abstract class AbstractGoo { public abstract long this[int x] { set; } public abstract long this[string x] { set; } public abstract long this[char x] { set; } } abstract class Goo : AbstractGoo { public long this[int x] { set { } } public abstract long this[string x] { set; } public virtual long this[char x] { set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractEvent() { var text = @" abstract class AbstractGoo { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } abstract class Goo : AbstractGoo { public event System.Action Event1 { add { } remove { } } public abstract event System.Action Event2; public virtual event System.Action Event3 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,32): error CS0533: 'Goo.Event1' hides inherited abstract member 'AbstractGoo.Event1' // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event1").WithArguments("Goo.Event1", "AbstractGoo.Event1"), // (11,32): warning CS0114: 'Goo.Event1' hides inherited member 'AbstractGoo.Event1'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event1").WithArguments("Goo.Event1", "AbstractGoo.Event1"), // (12,41): error CS0533: 'Goo.Event2' hides inherited abstract member 'AbstractGoo.Event2' // public abstract event System.Action Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event2").WithArguments("Goo.Event2", "AbstractGoo.Event2"), // (12,41): warning CS0114: 'Goo.Event2' hides inherited member 'AbstractGoo.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event2 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Goo.Event2", "AbstractGoo.Event2"), // (13,40): error CS0533: 'Goo.Event3' hides inherited abstract member 'AbstractGoo.Event3' // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event3").WithArguments("Goo.Event3", "AbstractGoo.Event3"), // (13,40): warning CS0114: 'Goo.Event3' hides inherited member 'AbstractGoo.Event3'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event3").WithArguments("Goo.Event3", "AbstractGoo.Event3")); } [Fact] public void TestNoMethodToOverride() { var text = @" interface Interface { void Method0(); } class Base { public virtual void Method1() { } private void Method2() { } } class Derived : Base, Interface { public override void Method0() { } public override void Method1(int x) { } public override void Method2() { } public override void Method3() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 16, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 18, Column = 26 }, }); } [Fact] public void TestNoPropertyToOverride() { var text = @" interface Interface { int Property0 { get; set; } } class Base { public virtual int Property1 { get; set; } private int Property2 { get; set; } public virtual int Property3 { get { return 0; } } public virtual int Property4 { get { return 0; } } public virtual int Property5 { set { } } public virtual int Property6 { set { } } public virtual int Property7 { get; set; } public virtual int Property8 { get; set; } } class Derived : Base, Interface { public override int Property0 { get; set; } //iface public override double Property1 { get; set; } //wrong type public override int Property2 { get; set; } //inaccessible public override int Property3 { set { } } //wrong accessor(s) public override int Property4 { get; set; } //wrong accessor(s) public override int Property5 { get { return 0; } } //wrong accessor(s) public override int Property6 { get; set; } //wrong accessor(s) public override int Property7 { get { return 0; } } //wrong accessor(s) public override int Property8 { set { } } //wrong accessor(s) public override int Property9 { get; set; } //nothing to override } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 21, Column = 25 }, //0 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 22, Column = 28 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 23, Column = 25 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 24, Column = 37 }, //3.set new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 25, Column = 42 }, //4.set new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 26, Column = 37 }, //5.get new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 27, Column = 37 }, //6.get new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 30, Column = 25 }, //9 }); } [Fact] public void TestNoIndexerToOverride() { var text = @" interface Interface { int this[long w, long x, long y, long z] { get; set; } } class Base { public virtual int this[long w, long x, long y, char z] { get { return 0; } set { } } private int this[long w, long x, char y, long z] { get { return 0; } set { } } public virtual int this[long w, long x, char y, char z] { get { return 0; } } public virtual int this[long w, char x, long y, long z] { get { return 0; } } public virtual int this[long w, char x, long y, char z] { set { } } public virtual int this[long w, char x, char y, long z] { set { } } public virtual int this[long w, char x, char y, char z] { get { return 0; } set { } } public virtual int this[char w, long x, long y, long z] { get { return 0; } set { } } } class Derived : Base, Interface { public override int this[long w, long x, long y, long z] { get { return 0; } set { } } //iface public override double this[long w, long x, long y, char z] { get { return 0; } set { } } //wrong type public override int this[long w, long x, char y, long z] { get { return 0; } set { } } //inaccessible public override int this[long w, long x, char y, char z] { set { } } //wrong accessor(s) public override int this[long w, char x, long y, long z] { get { return 0; } set { } } //wrong accessor(s) public override int this[long w, char x, long y, char z] { get { return 0; } } //wrong accessor(s) public override int this[long w, char x, char y, long z] { get { return 0; } set { } } //wrong accessor(s) public override int this[long w, char x, char y, char z] { get { return 0; } } //wrong accessor(s) public override int this[char w, long x, long y, long z] { set { } } //wrong accessor(s) public override int this[string s] { get { return 0; } set { } } //nothing to override } "; CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS0115: 'Derived.this[long, long, long, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long, long, long, long]"), // (22,28): error CS1715: 'Derived.this[long, long, long, char]': type must be 'int' to match overridden member 'Base.this[long, long, long, char]' Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[long, long, long, char]", "Base.this[long, long, long, char]", "int"), // (23,25): error CS0115: 'Derived.this[long, long, char, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long, long, char, long]"), // (24,64): error CS0546: 'Derived.this[long, long, char, char].set': cannot override because 'Base.this[long, long, char, char]' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[long, long, char, char].set", "Base.this[long, long, char, char]"), // (25,82): error CS0546: 'Derived.this[long, char, long, long].set': cannot override because 'Base.this[long, char, long, long]' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[long, char, long, long].set", "Base.this[long, char, long, long]"), // (26,64): error CS0545: 'Derived.this[long, char, long, char].get': cannot override because 'Base.this[long, char, long, char]' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[long, char, long, char].get", "Base.this[long, char, long, char]"), // (27,64): error CS0545: 'Derived.this[long, char, char, long].get': cannot override because 'Base.this[long, char, char, long]' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[long, char, char, long].get", "Base.this[long, char, char, long]"), // (30,25): error CS0115: 'Derived.this[string]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string]")); } [Fact] public void TestNoEventToOverride() { var text = @" interface Interface { event System.Action Event0; } class Base { public virtual event System.Action Event1 { add { } remove { } } private event System.Action Event2 { add { } remove { } } } class Derived : Base, Interface { public override event System.Action Event0 { add { } remove { } } //iface public override event System.Func<int> Event1 { add { } remove { } } //wrong type public override event System.Action Event2 { add { } remove { } } //inaccessible public override event System.Action Event3 { add { } remove { } } //nothing to override } "; CreateCompilation(text).VerifyDiagnostics( // (15,41): error CS0115: 'Derived.Event0': no suitable method found to override // public override event System.Action Event0 { add { } remove { } } //iface Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event0").WithArguments("Derived.Event0"), // (16,44): error CS1715: 'Derived.Event1': type must be 'System.Action' to match overridden member 'Base.Event1' // public override event System.Func<int> Event1 { add { } remove { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Event1").WithArguments("Derived.Event1", "Base.Event1", "System.Action"), // (17,41): error CS0115: 'Derived.Event2': no suitable method found to override // public override event System.Action Event2 { add { } remove { } } //inaccessible Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event2").WithArguments("Derived.Event2"), // (18,41): error CS0115: 'Derived.Event3': no suitable method found to override // public override event System.Action Event3 { add { } remove { } } //nothing to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event3").WithArguments("Derived.Event3")); } [Fact] public void TestSuppressOverrideNotExpectedErrorWhenMethodParameterTypeNotFound() { var text = @" class Base { } class Derived : Base { public override void Method0(String x) { } public override void Method1(string x, String y) { } public override void Method2(String[] x) { } public override void Method3(System.Func<String> x) { } public override void Method4((string a, String b) x) { } public override void Method5(System.Func<(string a, String[] b)> x) { } public override void Method6(Outer<String>.Inner<string> x) { } public override void Method7(Outer<string>.Inner<String> x) { } public override void Method8(Int? x) { } } class Outer<T> { public class Inner<U>{} } "; CreateCompilation(text).VerifyDiagnostics( // (8,34): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method0(String x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(8, 34), // (9,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method1(string x, String y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 44), // (10,34): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method2(String[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 34), // (11,46): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method3(System.Func<String> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 46), // (12,45): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method4((string a, String b) x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 45), // (13,57): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method5(System.Func<(string a, String[] b)> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 57), // (14,40): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method6(Outer<String>.Inner<string> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 40), // (15,54): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method7(Outer<string>.Inner<String> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 54), // (16,34): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override void Method8(Int? x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 34)); } [Fact] public void TestSuppressOverrideNotExpectedErrorWhenIndexerParameterTypeNotFound() { var text = @" class Base { } class Derived : Base { public override int this[String x] => 0; public override int this[string x, String y] => 0; public override int this[String[] x] => 0; public override int this[System.Func<String> x] => 0; public override int this[(string a, String b) x] => 0; public override int this[System.Func<(string a, String[] b)> x] => 0; public override int this[Outer<String>.Inner<string> x] => 0; public override int this[Outer<string>.Inner<String> x] => 0; public override int this[Int? x] => 0; } class Outer<T> { public class Inner<U>{} } "; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[String x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(8, 30), // (9,40): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[string x, String y] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 40), // (10,30): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[String[] x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 30), // (11,42): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[System.Func<String> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 42), // (12,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[(string a, String b) x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 41), // (13,53): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[System.Func<(string a, String[] b)> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 53), // (14,36): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Outer<String>.Inner<string> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 36), // (15,50): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Outer<string>.Inner<String> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 50), // (16,30): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Int? x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 30)); } [Fact] public void TestSuppressCantChangeReturnTypeErrorWhenMethodReturnTypeNotFound() { var text = @" abstract class Base { public abstract void Method0(); public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); public abstract void Method4(); public abstract void Method5(); public abstract void Method6(); public abstract void Method7(); } class Derived : Base { public override String Method0() => null; public override String[] Method1() => null; public override System.Func<String> Method2() => null; public override (string a, String b) Method3() => (null, null); public override System.Func<(string a, String[] b)> Method4() => null; public override Outer<String>.Inner<string> Method5() => null; public override Outer<string>.Inner<String> Method6() => null; public override Int? Method7() => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String Method0() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 21), // (17,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] Method1() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 21), // (18,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> Method2() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 33), // (19,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) Method3() => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 32), // (20,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> Method4() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 44), // (21,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> Method5() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 27), // (22,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> Method6() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 41), // (23,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? Method7() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 21)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenPropertyTypeNotFound() { var text = @" abstract class Base { public abstract int Property0 { get; } public abstract int Property1 { get; } public abstract int Property2 { get; } public abstract int Property3 { get; } public abstract int Property4 { get; } public abstract int Property5 { get; } public abstract int Property6 { get; } public abstract int Property7 { get; } } class Derived : Base { public override String Property0 => null; public override String[] Property1 => null; public override System.Func<String> Property2 => null; public override (string a, String b) Property3 => (null, null); public override System.Func<(string a, String[] b)> Property4 => null; public override Outer<String>.Inner<string> Property5 => null; public override Outer<string>.Inner<String> Property6 => null; public override Int? Property7 => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String Property0 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 21), // (17,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] Property1 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 21), // (18,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> Property2 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 33), // (19,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) Property3 => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 32), // (20,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> Property4 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 44), // (21,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> Property5 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 27), // (22,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> Property6 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 41), // (23,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? Property7 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 21)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenIndexerTypeNotFound() { var text = @" abstract class Base { public abstract int this[int index] { get; } } class Derived : Base { public override String this[int index] => null; public override String[] this[int index] => null; public override System.Func<String> this[int index] => null; public override (string a, String b) this[int index] => (null, null); public override System.Func<(string a, String[] b)> this[int index] => null; public override Outer<String>.Inner<string> this[int index] => null; public override Outer<string>.Inner<String> this[int index] => null; public override Int? this[int index] => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 21), // (10,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 21), // (11,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 33), // (12,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) this[int index] => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 32), // (13,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 44), // (14,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 27), // (15,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 41), // (16,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 21), // (10,30): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override String[] this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(10, 30), // (11,41): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override System.Func<String> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(11, 41), // (12,42): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override (string a, String b) this[int index] => (null, null); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(12, 42), // (13,57): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override System.Func<(string a, String[] b)> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(13, 57), // (14,49): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Outer<String>.Inner<string> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(14, 49), // (15,49): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Outer<string>.Inner<String> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(15, 49), // (16,26): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Int? this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(16, 26)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenEventTypeNotFound() { var text = @" abstract class Base { public abstract event System.Action Event0; public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; public abstract event System.Action Event4; public abstract event System.Action Event5; public abstract event System.Action Event6; public abstract event System.Action Event7; } class Derived : Base { public override event String Event0; public override event String[] Event1; public override event System.Func<String> Event2; public override event (string a, String b) Event3; public override event System.Func<(string a, String[] b)> Event4; public override event Outer<String>.Inner<string> Event5; public override event Outer<string>.Inner<String> Event6; public override event Int? Event7; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event String Event0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 27), // (17,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event String[] Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 27), // (18,39): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event System.Func<String> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 39), // (19,38): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event (string a, String b) Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 38), // (20,50): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event System.Func<(string a, String[] b)> Event4; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 50), // (21,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 33), // (22,47): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 47), // (23,27): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override event Int? Event7; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 27), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event6.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event6.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event5.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event5.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event4.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event4.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event4.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event4.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event7.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event7.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event0.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event0.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event6.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event6.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event7.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event7.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event0.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event0.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event5.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event5.remove").WithLocation(14, 7), // (17,36): error CS0066: 'Derived.Event1': event must be of a delegate type // public override event String[] Event1; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event1").WithArguments("Derived.Event1").WithLocation(17, 36), // (19,48): error CS0066: 'Derived.Event3': event must be of a delegate type // public override event (string a, String b) Event3; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event3").WithArguments("Derived.Event3").WithLocation(19, 48), // (21,55): error CS0066: 'Derived.Event5': event must be of a delegate type // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event5").WithArguments("Derived.Event5").WithLocation(21, 55), // (22,55): error CS0066: 'Derived.Event6': event must be of a delegate type // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event6").WithArguments("Derived.Event6").WithLocation(22, 55), // (23,32): error CS0066: 'Derived.Event7': event must be of a delegate type // public override event Int? Event7; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event7").WithArguments("Derived.Event7").WithLocation(23, 32), // (19,48): warning CS0067: The event 'Derived.Event3' is never used // public override event (string a, String b) Event3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event3").WithArguments("Derived.Event3").WithLocation(19, 48), // (23,32): warning CS0067: The event 'Derived.Event7' is never used // public override event Int? Event7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event7").WithArguments("Derived.Event7").WithLocation(23, 32), // (17,36): warning CS0067: The event 'Derived.Event1' is never used // public override event String[] Event1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event1").WithArguments("Derived.Event1").WithLocation(17, 36), // (22,55): warning CS0067: The event 'Derived.Event6' is never used // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event6").WithArguments("Derived.Event6").WithLocation(22, 55), // (18,47): warning CS0067: The event 'Derived.Event2' is never used // public override event System.Func<String> Event2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event2").WithArguments("Derived.Event2").WithLocation(18, 47), // (21,55): warning CS0067: The event 'Derived.Event5' is never used // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event5").WithArguments("Derived.Event5").WithLocation(21, 55), // (20,63): warning CS0067: The event 'Derived.Event4' is never used // public override event System.Func<(string a, String[] b)> Event4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event4").WithArguments("Derived.Event4").WithLocation(20, 63), // (16,34): warning CS0067: The event 'Derived.Event0' is never used // public override event String Event0; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event0").WithArguments("Derived.Event0").WithLocation(16, 34)); } [Fact] public void TestOverrideSealedMethod() { var text = @" class Base { public sealed override string ToString() { return ""Base""; } } class Derived : Base { public override string ToString() { return ""Derived""; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 12, Column = 28 }, }); } [Fact] public void TestOverrideSealedProperty() { var text = @" class Base0 { public virtual int Property { get; set; } } class Base : Base0 { public sealed override int Property { get; set; } } class Derived : Base { public override int Property { get; set; } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived.Property }); } [Fact] public void TestOverrideSealedIndexer() { var text = @" class Base0 { public virtual int this[int x] { get { return 0; } set { } } } class Base : Base0 { public sealed override int this[int x] { get { return 0; } set { } } } class Derived : Base { public override int this[int x] { get { return 0; } set { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the indexer itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived indexer }); } [Fact] public void TestOverrideSealedEvents() { var text = @" class Base0 { public virtual event System.Action Event { add { } remove { } } } class Base : Base0 { public sealed override event System.Action Event { add { } remove { } } } class Derived : Base { public override event System.Action Event { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,41): error CS0239: 'Derived.Event': cannot override inherited member 'Base.Event' because it is sealed // public override event System.Action Event { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Event").WithArguments("Derived.Event", "Base.Event")); } [Fact] public void TestOverrideSealedPropertyOmitAccessors() { var text = @" class Base0 { public virtual int Property { get; set; } } class Base : Base0 { public sealed override int Property { set { } } } class Derived : Base { public override int Property { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived.Property }); } [Fact] public void TestOverrideSealedIndexerOmitAccessors() { var text = @" class Base0 { public virtual int this[int x] { get { return 0; } set { } } } class Base : Base0 { public sealed override int this[int x] { set { } } } class Derived : Base { public override int this[int x] { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived indexer }); } [Fact] public void TestOverrideSameMemberMultipleTimes() { // Tests: // Override same virtual / abstract member more than once in different parts of a (partial) derived type var text = @" using str = System.String; class Base { public virtual string Method1() { return string.Empty; } public virtual string Method2() { return string.Empty; } } class Derived : Base { public override System.String Method1() { return null; } public override string Method1() { return null; } } partial class Derived2 : Base { public override string Method2() { return null; } } partial class Derived2 { public override string Method2() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,28): error CS0111: Type 'Derived' already defines a member called 'Method1' with the same parameter types // public override string Method1() { return null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method1").WithArguments("Method1", "Derived"), // (22,28): error CS0111: Type 'Derived2' already defines a member called 'Method2' with the same parameter types // public override string Method2() { return null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method2").WithArguments("Method2", "Derived2"), // (2,1): info CS8019: Unnecessary using directive. // using str = System.String; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using str = System.String;")); } [Fact] public void TestOverrideNonMethodWithMethod() { var text = @" class Base { public int field; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; } class Derived : Base { public override int field() { return 1; } public override int Property() { return 1; } public override int Interface() { return 1; } public override int Class() { return 1; } public override int Struct() { return 1; } public override int Enum() { return 1; } public override int Delegate() { return 1; } public override int Event() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,25): error CS0505: 'Derived.field()': cannot override because 'Base.field' is not a function // public override int field() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "field").WithArguments("Derived.field()", "Base.field"), // (17,25): error CS0505: 'Derived.Property()': cannot override because 'Base.Property' is not a function // public override int Property() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Property").WithArguments("Derived.Property()", "Base.Property"), // (18,25): error CS0505: 'Derived.Interface()': cannot override because 'Base.Interface' is not a function // public override int Interface() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Interface").WithArguments("Derived.Interface()", "Base.Interface"), // (19,25): error CS0505: 'Derived.Class()': cannot override because 'Base.Class' is not a function // public override int Class() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Class").WithArguments("Derived.Class()", "Base.Class"), // (20,25): error CS0505: 'Derived.Struct()': cannot override because 'Base.Struct' is not a function // public override int Struct() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Struct").WithArguments("Derived.Struct()", "Base.Struct"), // (21,25): error CS0505: 'Derived.Enum()': cannot override because 'Base.Enum' is not a function // public override int Enum() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Enum").WithArguments("Derived.Enum()", "Base.Enum"), // (22,25): error CS0505: 'Derived.Delegate()': cannot override because 'Base.Delegate' is not a function // public override int Delegate() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Delegate").WithArguments("Derived.Delegate()", "Base.Delegate"), // (23,25): error CS0505: 'Derived.Event()': cannot override because 'Base.Event' is not a function // public override int Event() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Event").WithArguments("Derived.Event()", "Base.Event"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0"), // (11,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event") ); } [Fact] public void TestOverrideNonPropertyWithProperty() { var text = @" class Base { public int field; public int Method() { return 0; } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; } class Derived : Base { public override int field { get; set; } public override int Method { get; set; } public override int Interface { get; set; } public override int Class { get; set; } public override int Struct { get; set; } public override int Enum { get; set; } public override int Delegate { get; set; } public override int Event { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,25): error CS0544: 'Derived.field': cannot override because 'Base.field' is not a property // public override int field { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "field").WithArguments("Derived.field", "Base.field"), // (17,25): error CS0544: 'Derived.Method': cannot override because 'Base.Method()' is not a property // public override int Method { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Method").WithArguments("Derived.Method", "Base.Method()"), // (18,25): error CS0544: 'Derived.Interface': cannot override because 'Base.Interface' is not a property // public override int Interface { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (19,25): error CS0544: 'Derived.Class': cannot override because 'Base.Class' is not a property // public override int Class { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Class").WithArguments("Derived.Class", "Base.Class"), // (20,25): error CS0544: 'Derived.Struct': cannot override because 'Base.Struct' is not a property // public override int Struct { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (21,25): error CS0544: 'Derived.Enum': cannot override because 'Base.Enum' is not a property // public override int Enum { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (22,25): error CS0544: 'Derived.Delegate': cannot override because 'Base.Delegate' is not a property // public override int Delegate { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (23,25): error CS0544: 'Derived.Event': cannot override because 'Base.Event' is not a property // public override int Event { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Event").WithArguments("Derived.Event", "Base.Event"), // (11,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0") ); } [Fact] public void TestOverrideNonEventWithEvent() { var text = @" class Base { public int field; public int Property { get { return 0; } } public int Method() { return 0; } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); } class Derived : Base { public override event System.Action field { add { } remove { } } public override event System.Action Property { add { } remove { } } public override event System.Action Method { add { } remove { } } public override event System.Action Interface { add { } remove { } } public override event System.Action Class { add { } remove { } } public override event System.Action Struct { add { } remove { } } public override event System.Action Enum { add { } remove { } } public override event System.Action Delegate { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (16,41): error CS0072: 'Derived.field': cannot override; 'Base.field' is not an event // public override event System.Action field { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "field").WithArguments("Derived.field", "Base.field"), // (17,41): error CS0072: 'Derived.Property': cannot override; 'Base.Property' is not an event // public override event System.Action Property { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Property").WithArguments("Derived.Property", "Base.Property"), // (18,41): error CS0072: 'Derived.Method': cannot override; 'Base.Method()' is not an event // public override event System.Action Method { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Method").WithArguments("Derived.Method", "Base.Method()"), // (19,41): error CS0072: 'Derived.Interface': cannot override; 'Base.Interface' is not an event // public override event System.Action Interface { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (20,41): error CS0072: 'Derived.Class': cannot override; 'Base.Class' is not an event // public override event System.Action Class { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Class").WithArguments("Derived.Class", "Base.Class"), // (21,41): error CS0072: 'Derived.Struct': cannot override; 'Base.Struct' is not an event // public override event System.Action Struct { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (22,41): error CS0072: 'Derived.Enum': cannot override; 'Base.Enum' is not an event // public override event System.Action Enum { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (23,41): error CS0072: 'Derived.Delegate': cannot override; 'Base.Delegate' is not an event // public override event System.Action Delegate { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0") ); } [Fact] public void TestOverrideNonVirtualMethod() { var text = @" class Base { public virtual void Method1() { } } class Derived : Base { public new void Method1() { } public void Method2() { } } class Derived2 : Derived { public override void Method1() { } public override void Method2() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualProperty() { var text = @" class Base { public virtual long Property1 { get; set; } } class Derived : Base { public new long Property1 { get; set; } public long Property2 { get; set; } } class Derived2 : Derived { public override long Property1 { get; set; } public override long Property2 { get; set; } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualIndexer() { var text = @" class Base { public virtual long this[int x] { get { return 0; } set { } } } class Derived : Base { public new long this[int x] { get { return 0; } set { } } public long this[string x] { get { return 0; } set { } } } class Derived2 : Derived { public override long this[int x] { get { return 0; } set { } } public override long this[string x] { get { return 0; } set { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the indexer itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualPropertyOmitAccessors() { var text = @" class Base { public virtual long Property1 { get; set; } } class Derived : Base { public new long Property1 { get { return 0; } } public long Property2 { get; set; } } class Derived2 : Derived { public override long Property1 { set { } } public override long Property2 { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualIndexerOmitAccessors() { var text = @" class Base { public virtual long this[int x] { get { return 0; } set { } } } class Derived : Base { public new long this[int x] { get { return 0; } } public long this[string x] { get { return 0; } set { } } } class Derived2 : Derived { public override long this[int x] { set { } } public override long this[string x] { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualEvent() { var text = @" class Base { public virtual event System.Action Event1 { add { } remove { } } } class Derived : Base { public new event System.Action Event1 { add { } remove { } } public event System.Action Event2 { add { } remove { } } } class Derived2 : Derived { public override event System.Action Event1 { add { } remove { } } public override event System.Action Event2 { add { } remove { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 41 }, }); } [Fact] public void TestChangeMethodReturnType() { var text = @" using str = System.String; class Base { public virtual string Method1() { return string.Empty; } public virtual string Method2() { return string.Empty; } public virtual string Method3() { return string.Empty; } public virtual string Method4() { return string.Empty; } public virtual string Method5() { return string.Empty; } } class Derived : Base { public override System.String Method1() { return null; } public override str Method2() { return null; } public override object Method3() { return null; } public override int Method4() { return 0; } public override void Method5() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 17, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 18, Column = 25 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 19, Column = 26 }, //5 }); } [Fact] public void TestChangeMethodRefReturn() { var text = @" class Base { public virtual int Method1() { return 0; } public virtual ref int Method2(ref int i) { return ref i; } public virtual ref int Method3(ref int i) { return ref i; } } class Derived : Base { int field = 0; public override ref int Method1() { return ref field; } public override int Method2(ref int i) { return i; } public override ref int Method3(ref int i) { return ref i; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,29): error CS8148: 'Derived.Method1()' must match by reference return of overridden member 'Base.Method1()' // public override ref int Method1() { return ref field; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method1").WithArguments("Derived.Method1()", "Base.Method1()").WithLocation(13, 29), // (14,25): error CS8148: 'Derived.Method2(ref int)' must match by reference return of overridden member 'Base.Method2(ref int)' // public override int Method2(ref int i) { return i; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method2").WithArguments("Derived.Method2(ref int)", "Base.Method2(ref int)").WithLocation(14, 25)); } [Fact] public void TestChangeMethodParameters() { // Tests: // Change parameter count / types of overridden member // Omit / toggle ref / out in overridden member // Override base member with a signature that only differs by optional parameters // Override base member with a signature that only differs by params // Change default value of optional argument in overridden member var text = @" using str = System.String; using integer = System.Int32; abstract class Base { public virtual string Method1(int i) { return string.Empty; } public virtual string Method2(long j) { return string.Empty; } public virtual string Method2(short j) { return string.Empty; } public virtual string Method3(System.Exception x, System.ArgumentException y) { return string.Empty; } public virtual string Method3(System.ArgumentException x, System.Exception y) { return string.Empty; } public abstract string Method4(str[] x, str[][] y); public abstract string Method5(System.Collections.Generic.List<str> x, System.Collections.Generic.Dictionary<int, long> y); public virtual string Method6(int i, params long[] j) { return string.Empty; } public virtual string Method7(int i, short j = 1) { return string.Empty; } public virtual string Method8(ref long j) { return string.Empty; } public abstract string Method9(out int j); } abstract class Derived : Base { public override str Method1(int i, long j = 1) { return string.Empty; } public override str Method1(int i, params int[] j) { return string.Empty; } public override str Method1(double i) { return string.Empty; } public override str Method2(int j) { return string.Empty; } public override str Method3(System.Exception x, System.ArgumentException y, System.Exception z) { return string.Empty; } public override str Method3(System.ArgumentException x, System.ArgumentException y) { return string.Empty; } public override str Method3() { return string.Empty; } public override str Method3(System.Exception x) { return string.Empty; } public override str Method4(str[] x, str[] y) { return string.Empty; } public override str Method4(str[][] y, str[] x) { return string.Empty; } public override str Method4(str[] x) { return string.Empty; } public override str Method5(System.Collections.Generic.List<int> x, System.Collections.Generic.Dictionary<str, long> y) { return string.Empty; } public override str Method5(System.Collections.Generic.Dictionary<int, long> x, System.Collections.Generic.List<string> y) { return string.Empty; } public override str Method5(System.Collections.Generic.List<string> y, System.Collections.Generic.Dictionary<integer, long> x) { return string.Empty; } // Not an error public override str Method6(int i, long j = 1) { return string.Empty; } public override str Method6(int i) { return string.Empty; } public override str Method7(int i, params short[] j) { return string.Empty; } public override str Method7(int i) { return string.Empty; } public override str Method7(int i, short j = 1, short k = 1) { return string.Empty; } public override str Method8(out long j) { j = 1; return string.Empty; } public override str Method8(long j) { return string.Empty; } public override str Method9(ref int j) { return string.Empty; } public override str Method9(int j) { return string.Empty; } public override str Method1(ref int i) { return string.Empty; } public override str Method2(out long j) { j = 2; return string.Empty; } public override str Method7(int i, short j = short.MaxValue) { return string.Empty; } // Not an error } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 20, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 21, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 22, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 23, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 24, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 25, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 26, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 27, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 28, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 29, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 30, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 31, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 32, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 34, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 35, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 36, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 37, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 38, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 39, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 41, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 42, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 43, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 44, Column = 25 } }); } [Fact] public void TestChangePropertyType() { var text = @" using str = System.String; class Base { public virtual string Property1 { get; set; } public virtual string Property2 { get; set; } public virtual string Property3 { get; set; } public virtual string Property4 { get; set; } } class Derived : Base { public override System.String Property1 { get; set; } public override str Property2 { get; set; } public override object Property3 { get; set; } public override int Property4 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 25 }, //4 }); } [Fact] public void TestChangePropertyRefReturn() { var text = @" class Base { int field = 0; public virtual int Proprty1 { get { return 0; } } public virtual ref int Property2 { get { return ref field; } } public virtual ref int Property3 { get { return ref field; } } } class Derived : Base { int field = 0; public override ref int Proprty1 { get { return ref field; } } public override int Property2 { get { return 0; } } public override ref int Property3 { get { return ref field; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,29): error CS8148: 'Derived.Proprty1' must match by reference return of overridden member 'Base.Proprty1' // public override ref int Proprty1 { get { return ref field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Proprty1").WithArguments("Derived.Proprty1", "Base.Proprty1").WithLocation(15, 29), // (16,25): error CS8148: 'Derived.Property2' must match by reference return of overridden member 'Base.Property2' // public override int Property2 { get { return 0; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property2").WithArguments("Derived.Property2", "Base.Property2").WithLocation(16, 25)); } [Fact] public void TestChangeIndexerType() { var text = @" using str = System.String; class Base { public virtual string this[int x, int y] { get { return null; } set { } } public virtual string this[int x, string y] { get { return null; } set { } } public virtual string this[string x, int y] { get { return null; } set { } } public virtual string this[string x, string y] { get { return null; } set { } } } class Derived : Base { public override System.String this[int x, int y] { get { return null; } set { } } public override str this[int x, string y] { get { return null; } set { } } public override object this[string x, int y] { get { return null; } set { } } public override int this[string x, string y] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 25 }, //4 }); } [Fact] public void TestChangeIndexerRefReturn() { var text = @" class Base { int field = 0; public virtual int this[int x, int y] { get { return field; } } public virtual ref int this[int x, string y] { get { return ref field; } } public virtual ref int this[string x, int y] { get { return ref field; } } } class Derived : Base { int field = 0; public override ref int this[int x, int y] { get { return ref field; } } public override int this[int x, string y] { get { return field; } } public override ref int this[string x, int y] { get { return ref field; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,29): error CS8148: 'Derived.this[int, int]' must match by reference return of overridden member 'Base.this[int, int]' // public override ref int this[int x, int y] { get { return ref field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[int, int]", "Base.this[int, int]").WithLocation(15, 29), // (16,25): error CS8148: 'Derived.this[int, string]' must match by reference return of overridden member 'Base.this[int, string]' // public override int this[int x, string y] { get { return field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[int, string]", "Base.this[int, string]").WithLocation(16, 25)); } /// <summary> /// Based on Method1 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters1() { var text = @" abstract class Base { public virtual string this[int i] { set { } } } abstract class Derived : Base { public override string this[int i, long j = 1] { set { } } public override string this[int i, params int[] j] { set { } } public override string this[double i] { set { } } public override string this[ref int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,28): error CS0115: 'Derived.this[int, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, long]"), // (9,28): error CS0115: 'Derived.this[int, params int[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, params int[]]"), // (10,28): error CS0115: 'Derived.this[double]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[double]"), // (11,28): error CS0115: 'Derived.this[ref int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[ref int]")); } /// <summary> /// Based on Method2 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters2() { var text = @" abstract class Base { public virtual string this[long j] { set { } } public virtual string this[short j] { set { } } } abstract class Derived : Base { public override string this[int j] { set { } } public override string this[out long j] { set { j = 2; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]"), // (10,28): error CS0115: 'Derived.this[out long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[out long]")); } /// <summary> /// Based on Method3 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters3() { var text = @" abstract class Base { public virtual string this[System.Exception x, System.ArgumentException y] { set { } } public virtual string this[System.ArgumentException x, System.Exception y] { set { } } } abstract class Derived : Base { public override string this[System.Exception x, System.ArgumentException y, System.Exception z] { set { } } public override string this[System.ArgumentException x, System.ArgumentException y] { set { } } public override string this[] { set { } } public override string this[System.Exception x] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,33): error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "]"), // (9,28): error CS0115: 'Derived.this[System.Exception, System.ArgumentException, System.Exception]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Exception, System.ArgumentException, System.Exception]"), // (10,28): error CS0115: 'Derived.this[System.ArgumentException, System.ArgumentException]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.ArgumentException, System.ArgumentException]"), // (11,28): error CS0115: 'Derived.this': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this"), // (12,28): error CS0115: 'Derived.this[System.Exception]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Exception]")); } /// <summary> /// Based on Method4 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters4() { var text = @" abstract class Base { public abstract string this[string[] x, string[][] y] { set; } } abstract class Derived : Base { public override string this[string[] x, string[] y] { set { } } public override string this[string[][] y, string[] x] { set { } } public override string this[string[] x] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[string[], string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[], string[]]"), // (9,28): error CS0115: 'Derived.this[string[][], string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[][], string[]]"), // (10,28): error CS0115: 'Derived.this[string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[]]")); } /// <summary> /// Based on Method5 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters5() { var text = @" abstract class Base { public abstract string this[System.Collections.Generic.List<string> x, System.Collections.Generic.Dictionary<int, long> y] { set; } } abstract class Derived : Base { public override string this[System.Collections.Generic.List<int> x, System.Collections.Generic.Dictionary<string, long> y] { set { } } public override string this[System.Collections.Generic.Dictionary<int, long> x, System.Collections.Generic.List<string> y] { set { } } public override string this[System.Collections.Generic.List<string> y, System.Collections.Generic.Dictionary<int, long> x] { set { } } // Not an error } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<string, long>]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<string, long>]"), // (9,28): error CS0115: 'Derived.this[System.Collections.Generic.Dictionary<int, long>, System.Collections.Generic.List<string>]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Collections.Generic.Dictionary<int, long>, System.Collections.Generic.List<string>]")); } /// <summary> /// Based on Method6 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters6() { var text = @" abstract class Base { public virtual string this[int i, params long[] j] { set { } } } abstract class Derived : Base { public override string this[int i, long j = 1] { set { } } public override string this[int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[int, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, long]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]")); } /// <summary> /// Based on Method7 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters7() { var text = @" abstract class Base { public virtual string this[int i, short j = 1] { set { } } } abstract class Derived : Base { public override string this[int i, params short[] j] { set { } } public override string this[int i] { set { } } public override string this[int i, short j = 1, short k = 1] { set { } } public override string this[int i, short j = short.MaxValue] { set { } } // Not an error } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[int, params short[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, params short[]]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]"), // (10,28): error CS0115: 'Derived.this[int, short, short]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, short, short]")); } /// <summary> /// Based on Method8 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters8() { var text = @" abstract class Base { public virtual string this[ref long j] { set { } } } abstract class Derived : Base { public override string this[out long j] { set { j = 1; } } public override string this[long j] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,32): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (8,28): error CS0115: 'Derived.this[out long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[out long]"), // (9,28): error CS0115: 'Derived.this[long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long]")); } /// <summary> /// Based on Method9 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters9() { var text = @" abstract class Base { public abstract string this[out int j] { set; } } abstract class Derived : Base { public override string this[ref int j] { set { } } public override string this[int j] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (8,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,28): error CS0115: 'Derived.this[ref int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[ref int]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]")); } [Fact] public void TestChangeEventType() { var text = @" using str = System.String; class Base { public virtual event System.Action<string> Event1 { add { } remove { } } public virtual event System.Action<string> Event2 { add { } remove { } } public virtual event System.Action<string> Event3 { add { } remove { } } public virtual event System.Action<string> Event4 { add { } remove { } } } class Derived : Base { public override event System.Action<System.String> Event1 { add { } remove { } } public override event System.Action<str> Event2 { add { } remove { } } public override event System.Action<object> Event3 { add { } remove { } } public override event System.Action<int> Event4 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 49 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 46 }, //4 }); } [Fact] public void TestChangeGenericMethodReturnType() { var text = @" class Base<T> { public virtual T Method1(T t) { return t; } public virtual U Method2<U>(U u) { return u; } } class Derived : Base<string> { public override object Method1(string t) { return null; } public override object Method2<U>(U u) { return null; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 10, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 11, Column = 28 }, }); } [Fact] public void TestChangeGenericMethodParameters() { // Tests: // Change number / order / types of method parameters in overridden method var text = @" using System.Collections.Generic; abstract class Base<T, U> { protected virtual void Method(T x) { } protected virtual void Method(List<T> x) { } protected virtual void Method<V>(V x, T y) { } protected virtual void Method<V>(List<V> x, List<U> y) { } } class Derived<A, B> : Base<A, B> { protected override void Method(B x) { } protected override void Method(List<B> x) { } protected override void Method<V>(A x, V y) { } protected override void Method<V>(List<V> x, List<A> y) { } protected override void Method<V, U>(List<V> x, List<U> y) { } } class Derived : Base<long, int> { protected override void Method(int x) { } protected override void Method(List<int> x) { } protected override void Method<V>(int x, long y) { } protected override void Method<V>(List<V> x, List<long> y) { } protected override void Method<V>(List<long> x, List<int> y) { } } class Derived<A, B, C> : Base<A, B> { protected override void Method() { } protected override void Method(List<A> x, List<B> y) { } protected override void Method<V>(V x, A y, C z) { } protected override void Method<V>(List<V> x, ref List<B> y) { } protected override void Method<V>(List<V> x, List<B> y = null) { } // Not an error protected override void Method<V>(List<V> x, List<B>[] y) { } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method(B)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method(System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V>(A, V)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<A>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V, U>(System.Collections.Generic.List<V>, System.Collections.Generic.List<U>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(System.Collections.Generic.List<int>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, long)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<long>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(System.Collections.Generic.List<long>, System.Collections.Generic.List<int>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method(System.Collections.Generic.List<A>, System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(V, A, C)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(System.Collections.Generic.List<V>, ref System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<B>[])")); } [Fact] public void TestChangeGenericMethodTypeParameters() { // Tests: // Change number / order of generic method type parameters in overridden method var text = @" using System.Collections.Generic; class Base<T, U> { protected virtual void Method<V>() { } protected virtual void Method<V>(V x, T y) { } protected virtual void Method<V, W>(T x, U y) { } protected virtual void Method<V, W>(List<V> x, List<W> y) { } } class Derived : Base<int, int> { protected override void Method() { } protected override void Method<V, U>() { } protected override void Method<V>(int x, V y) { } protected override void Method<V, U>(V x, int y) { } protected override void Method(int x, int y) { } protected override void Method<V>(int x, int y) { } protected override void Method<V, U, W>(int x, int y) { } protected override void Method<V, W>(List<W> x, List<V> y) { } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U>()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, V)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U>(V, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U, W>(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, W>(System.Collections.Generic.List<W>, System.Collections.Generic.List<V>)")); } [Fact] public void TestChangeGenericPropertyType() { var text = @" class Base<T> { public virtual T Property1 { get; set; } public virtual T Property2 { get; set; } } class Derived : Base<string> { public override string Property1 { get; set; } public override object Property2 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 11, Column = 28 }, //2 }); } [Fact] public void TestChangeGenericIndexerType() { var text = @" class Base<T> { public virtual T this[int x] { get { return default(T); } set { } } public virtual T this[string x] { get { return default(T); } set { } } } class Derived : Base<string> { public override string this[int x] { get { return null; } set { } } public override object this[string x] { get { return null; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS1715: 'Derived.this[string]': type must be 'string' to match overridden member 'Base<string>.this[string]' Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[string]", "Base<string>.this[string]", "string")); } [Fact] public void TestChangeGenericIndexerParameters() { var text = @" class Base<T> { public virtual int this[string x, T y] { get { return 0; } set { } } public virtual int this[object x, T y] { get { return 0; } set { } } } class Derived : Base<string> { public override int this[string x, string y] { get { return 0; } set { } } public override int this[object x, object y] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0115: 'Derived.this[object, object]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[object, object]")); } [Fact] public void TestChangeGenericEventType() { var text = @" class Base<T> { public virtual event System.Action<T> Event1 { add { } remove { } } public virtual event System.Action<T> Event2 { add { } remove { } } } class Derived : Base<string> { public override event System.Action<string> Event1 { add { } remove { } } public override event System.Action<object> Event2 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 11, Column = 49 }, //2 }); } [Fact] public void TestDoNotChangeGenericMethodReturnType() { var text = @" interface IGoo<A> { } class Base { public virtual T Method1<T>(T t) { return t; } public virtual IGoo<U> Method2<U>(U u) { return null; } } class Derived : Base { public override M Method1<M>(M t) { return t; } public override IGoo<X> Method2<X>(X u) { return null; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { }); } [Fact] public void TestClassTypeParameterReturnType() { var text = @" class Base<T> { public virtual T Property { get; set; } public virtual T Method(T t) { return t; } } class Derived<S> : Base<S> { public override S Property { get; set; } public override S Method(S s) { return s; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { }); } [Fact] public void TestNoImplementationOfAbstractMethod() { var text = @" abstract class Base { public abstract object Method1(); public abstract object Method2(); public abstract object Method3(); public abstract object Method4(int i); public abstract ref object Method5(ref object o); public abstract object Method6(ref object o); } class Derived : Base { //missed Method1 entirely public object Method2() { return null; } //missed override keyword public int Method3() { return 0; } //wrong return type public object Method4(long l) { return 0; } //wrong signature public override object Method5(ref object o) { return null; } //wrong by-value return public override ref object Method6(ref object o) { return ref o; } //wrong by-ref return } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (16,16): warning CS0114: 'Derived.Method3()' hides inherited member 'Base.Method3()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Method3() { return 0; } //wrong return type Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method3").WithArguments("Derived.Method3()", "Base.Method3()").WithLocation(16, 16), // (18,28): error CS8148: 'Derived.Method5(ref object)' must match by reference return of overridden member 'Base.Method5(ref object)' // public override object Method5(ref object o) { return null; } //wrong by-value return Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method5").WithArguments("Derived.Method5(ref object)", "Base.Method5(ref object)").WithLocation(18, 28), // (19,32): error CS8148: 'Derived.Method6(ref object)' must match by reference return of overridden member 'Base.Method6(ref object)' // public override ref object Method6(ref object o) { return ref o; } //wrong by-ref return Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method6").WithArguments("Derived.Method6(ref object)", "Base.Method6(ref object)").WithLocation(19, 32), // (15,19): warning CS0114: 'Derived.Method2()' hides inherited member 'Base.Method2()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object Method2() { return null; } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method2").WithArguments("Derived.Method2()", "Base.Method2()").WithLocation(15, 19), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method2()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method2()").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method4(int)' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method4(int)").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method3()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method3()").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method1()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method1()").WithLocation(12, 7)); } [Fact] public void TestNoImplementationOfAbstractProperty() { var text = @" abstract class Base { public abstract object Property1 { get; set; } public abstract object Property2 { get; set; } public abstract object Property3 { get; set; } public abstract object Property4 { get; set; } public abstract object Property5 { get; set; } public abstract object Property6 { get; } public abstract object Property7 { get; } public abstract object Property8 { set; } public abstract object Property9 { set; } public abstract object Property10 { get; } public abstract ref object Property11 { get; } } class Derived : Base { //missed Property1 entirely public object Property2 { get; set; } //missed override keyword public override int Property3 { get; set; } //wrong type //wrong accessors public override object Property4 { get { return null; } } public override object Property5 { set { } } public override object Property6 { get; set; } public override object Property7 { set { } } public override object Property8 { get; set; } public override object Property9 { get { return null; } } //wrong by-{value,ref} return object o = null; public override ref object Property10 { get { return ref o; } } public override object Property11 { get { return null; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (23,25): error CS1715: 'Derived.Property3': type must be 'object' to match overridden member 'Base.Property3' // public override int Property3 { get; set; } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Property3").WithArguments("Derived.Property3", "Base.Property3", "object").WithLocation(23, 25), // (28,45): error CS0546: 'Derived.Property6.set': cannot override because 'Base.Property6' does not have an overridable set accessor // public override object Property6 { get; set; } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.Property6.set", "Base.Property6").WithLocation(28, 45), // (29,40): error CS0546: 'Derived.Property7.set': cannot override because 'Base.Property7' does not have an overridable set accessor // public override object Property7 { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.Property7.set", "Base.Property7").WithLocation(29, 40), // (30,40): error CS0545: 'Derived.Property8.get': cannot override because 'Base.Property8' does not have an overridable get accessor // public override object Property8 { get; set; } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.Property8.get", "Base.Property8").WithLocation(30, 40), // (31,40): error CS0545: 'Derived.Property9.get': cannot override because 'Base.Property9' does not have an overridable get accessor // public override object Property9 { get { return null; } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.Property9.get", "Base.Property9").WithLocation(31, 40), // (35,32): error CS8148: 'Derived.Property10' must match by reference return of overridden member 'Base.Property10' // public override ref object Property10 { get { return ref o; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property10").WithArguments("Derived.Property10", "Base.Property10").WithLocation(35, 32), // (36,28): error CS8148: 'Derived.Property11' must match by reference return of overridden member 'Base.Property11' // public override object Property11 { get { return null; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property11").WithArguments("Derived.Property11", "Base.Property11").WithLocation(36, 28), // (22,19): warning CS0114: 'Derived.Property2' hides inherited member 'Base.Property2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object Property2 { get; set; } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Property2").WithArguments("Derived.Property2", "Base.Property2").WithLocation(22, 19), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property2.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property2.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property1.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property1.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property5.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property5.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property9.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property9.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property1.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property1.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property7.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property7.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property3.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property3.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property2.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property2.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property4.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property4.set").WithLocation(19, 7)); } [Fact] public void TestNoImplementationOfAbstractIndexer() { var text = @" abstract class Base { public abstract object this[int w, int x, int y , int z] { get; set; } public abstract object this[int w, int x, int y , string z] { get; set; } public abstract object this[int w, int x, string y , int z] { get; set; } public abstract object this[int w, int x, string y , string z] { get; set; } public abstract object this[int w, string x, int y , int z] { get; set; } public abstract object this[int w, string x, int y , string z] { get; } public abstract object this[int w, string x, string y , int z] { get; } public abstract object this[int w, string x, string y , string z] { set; } public abstract object this[string w, int x, int y , int z] { set; } public abstract object this[string w, int x, int y, string z] { get; } public abstract ref object this[string w, int x, string y, int z] { get; } } class Derived : Base { //missed first indexer entirely public object this[int w, int x, int y , string z] { get { return 0; } set { } } //missed override keyword public override int this[int w, int x, string y , int z] { get { return 0; } set { } } //wrong type //wrong accessors public override object this[int w, int x, string y , string z] { get { return null; } } public override object this[int w, string x, int y , int z] { set { } } public override object this[int w, string x, int y , string z] { get { return 0; } set { } } public override object this[int w, string x, string y , int z] { set { } } public override object this[int w, string x, string y , string z] { get { return 0; } set { } } public override object this[string w, int x, int y , int z] { get { return null; } } //wrong by-{value,ref} return object o = null; public override ref object this[string w, int x, int y, string z] { get { return ref o; } } public override object this[string w, int x, string y, int z] { get; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (36,69): error CS0501: 'Derived.this[string, int, string, int].get' must declare a body because it is not marked abstract, extern, or partial // public override object this[string w, int x, string y, int z] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("Derived.this[string, int, string, int].get").WithLocation(36, 69), // (23,25): error CS1715: 'Derived.this[int, int, string, int]': type must be 'object' to match overridden member 'Base.this[int, int, string, int]' // public override int this[int w, int x, string y , int z] { get { return 0; } set { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[int, int, string, int]", "Base.this[int, int, string, int]", "object").WithLocation(23, 25), // (28,88): error CS0546: 'Derived.this[int, string, int, string].set': cannot override because 'Base.this[int, string, int, string]' does not have an overridable set accessor // public override object this[int w, string x, int y , string z] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[int, string, int, string].set", "Base.this[int, string, int, string]").WithLocation(28, 88), // (29,70): error CS0546: 'Derived.this[int, string, string, int].set': cannot override because 'Base.this[int, string, string, int]' does not have an overridable set accessor // public override object this[int w, string x, string y , int z] { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[int, string, string, int].set", "Base.this[int, string, string, int]").WithLocation(29, 70), // (30,73): error CS0545: 'Derived.this[int, string, string, string].get': cannot override because 'Base.this[int, string, string, string]' does not have an overridable get accessor // public override object this[int w, string x, string y , string z] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[int, string, string, string].get", "Base.this[int, string, string, string]").WithLocation(30, 73), // (31,67): error CS0545: 'Derived.this[string, int, int, int].get': cannot override because 'Base.this[string, int, int, int]' does not have an overridable get accessor // public override object this[string w, int x, int y , int z] { get { return null; } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[string, int, int, int].get", "Base.this[string, int, int, int]").WithLocation(31, 67), // (35,32): error CS8148: 'Derived.this[string, int, int, string]' must match by reference return of overridden member 'Base.this[string, int, int, string]' // public override ref object this[string w, int x, int y, string z] { get { return ref o; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[string, int, int, string]", "Base.this[string, int, int, string]").WithLocation(35, 32), // (36,28): error CS8148: 'Derived.this[string, int, string, int]' must match by reference return of overridden member 'Base.this[string, int, string, int]' // public override object this[string w, int x, string y, int z] { get; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[string, int, string, int]", "Base.this[string, int, string, int]").WithLocation(36, 28), // (22,19): warning CS0114: 'Derived.this[int, int, int, string]' hides inherited member 'Base.this[int, int, int, string]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object this[int w, int x, int y , string z] { get { return 0; } set { } } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("Derived.this[int, int, int, string]", "Base.this[int, int, int, string]").WithLocation(22, 19), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, string, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, string, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, string, string].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, string, string].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, int].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, string, int, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, string, int, int].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, string].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, string].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, string].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, string].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[string, int, int, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[string, int, int, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, string, string, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, string, string, int].get").WithLocation(19, 7)); } [Fact] public void TestNoImplementationOfAbstractEvent() { var text = @" abstract class Base { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } class Derived : Base { //missed Method1 Event1 public event System.Action Event2 { add { } remove { } } //missed override keyword public override event System.Action<int> Event3 { add { } remove { } } //wrong type } "; CreateCompilation(text).VerifyDiagnostics( // (12,32): warning CS0114: 'Derived.Event2' hides inherited member 'Base.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event2 { add { } remove { } } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (13,46): error CS1715: 'Derived.Event3': type must be 'System.Action' to match overridden member 'Base.Event3' // public override event System.Action<int> Event3 { add { } remove { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Event3").WithArguments("Derived.Event3", "Base.Event3", "System.Action"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.remove"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.remove"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.remove")); } [Fact] public void TestNoImplementationOfAbstractMethodFromGrandparent() { var text = @" abstract class Abstract1 { public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); } abstract class Abstract2 : Abstract1 { public override void Method1() { } public abstract void Method4(); public abstract void Method5(); } class Concrete : Abstract2 { public override void Method3() { } public override void Method5() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //Method2 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //Method4 }); } [Fact] public void TestNoImplementationOfAbstractPropertyFromGrandparent() { var text = @" abstract class Abstract1 { public abstract long Property1 { get; set; } public abstract long Property2 { get; set; } public abstract long Property3 { get; set; } } abstract class Abstract2 : Abstract1 { public override long Property1 { get; set; } public abstract long Property4 { get; set; } public abstract long Property5 { get; set; } } class Concrete : Abstract2 { public override long Property3 { get; set; } public override long Property5 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.get new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.set new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.get new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.set }); } [Fact] public void TestNoImplementationOfAbstractIndexerFromGrandparent() { var text = @" abstract class Abstract1 { public abstract long this[int x, int y, string z] { get; set; } public abstract long this[int x, string y, int z] { get; set; } public abstract long this[int x, string y, string z] { get; set; } } abstract class Abstract2 : Abstract1 { public override long this[int x, int y, string z] { get { return 0; } set { } } public abstract long this[string x, int y, int z] { get; set; } public abstract long this[string x, int y, string z] { get; set; } } class Concrete : Abstract2 { public override long this[int x, string y, string z] { get { return 0; } set { } } public override long this[string x, int y, string z] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract1.this[int, string, int].get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract1.this[int, string, int].get"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract1.this[int, string, int].set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract1.this[int, string, int].set"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract2.this[string, int, int].get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract2.this[string, int, int].get"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract2.this[string, int, int].set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract2.this[string, int, int].set")); } [Fact] public void TestNoImplementationOfAbstractEventFromGrandparent() { var text = @" abstract class Abstract1 { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } abstract class Abstract2 : Abstract1 { public override event System.Action Event1 { add { } remove { } } public abstract event System.Action Event4; public abstract event System.Action Event5; } class Concrete : Abstract2 { public override event System.Action Event3 { add { } remove { } } public override event System.Action Event5 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.add new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.remove new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.add new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.remove }); } [Fact] public void TestNoImplementationOfInterfaceMethod_01() { var text = @" interface Interface { object Method1(); object Method2(int i); ref object Method3(ref object o); object Method4(ref object o); } class Class : Interface { //missed Method1 entirely public object Method2(long l) { return 0; } //wrong signature public object Method3(ref object o) { return null; } //wrong by-value return public ref object Method4(ref object o) { return ref o; } //wrong by-ref return } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (10,15): error CS8152: 'Class' does not implement interface member 'Interface.Method4(ref object)'. 'Class.Method4(ref object)' cannot implement 'Interface.Method4(ref object)' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Method4(ref object)", "Class.Method4(ref object)").WithLocation(10, 15), // (10,15): error CS0535: 'Class' does not implement interface member 'Interface.Method2(int)' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Method2(int)").WithLocation(10, 15), // (10,15): error CS8152: 'Class' does not implement interface member 'Interface.Method3(ref object)'. 'Class.Method3(ref object)' cannot implement 'Interface.Method3(ref object)' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Method3(ref object)", "Class.Method3(ref object)").WithLocation(10, 15), // (10,15): error CS0535: 'Class' does not implement interface member 'Interface.Method1()' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Method1()").WithLocation(10, 15)); } [Fact] public void TestNoImplementationOfInterfaceMethod_02() { var source1 = @" public class C1 {} "; var comp11 = CreateCompilation(new AssemblyIdentity("lib1", new Version("4.2.1.0"), publicKeyOrToken: SigningTestHelpers.PublicKey, hasPublicKey: true), new[] { source1 }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, null).ToArray(), TestOptions.DebugDll.WithPublicSign(true)); comp11.VerifyDiagnostics(); var comp12 = CreateCompilation(new AssemblyIdentity("lib1", new Version("4.1.0.0"), publicKeyOrToken: SigningTestHelpers.PublicKey, hasPublicKey: true), new[] { source1 }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, null).ToArray(), TestOptions.DebugDll.WithPublicSign(true)); comp12.VerifyDiagnostics(); var source2 = @" public class C2 : C1 {} "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp12.EmitToImageReference() }, assemblyName: "lib2"); comp2.VerifyDiagnostics(); var source3 = @" interface I1 { void Method1(); } #pragma warning disable CS1701 class C3 : C2, #pragma warning restore CS1701 I1 { } "; var comp3 = CreateCompilation(new[] { source3 }, references: new[] { comp11.EmitToImageReference(), comp2.EmitToImageReference() }, assemblyName: "lib3"); // The unification warning shouldn't suppress the CS0535 error. comp3.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'lib2' matches identity 'lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'lib1', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib2", "lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib1").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'lib2' matches identity 'lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'lib1', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib2", "lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib1").WithLocation(1, 1), // (10,16): error CS0535: 'C3' does not implement interface member 'I1.Method1()' // I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C3", "I1.Method1()").WithLocation(10, 16) ); } [Fact] public void TestNoImplementationOfInterfaceProperty() { var text = @" interface Interface { object Property1 { get; set; } object Property2 { get; set; } object Property3 { get; set; } object Property4 { get; } object Property5 { get; } object Property6 { set; } object Property7 { set; } ref object Property8 { get; } object Property9 { get; } } class Class : Interface { //missed Property1 entirely //wrong accessors public object Property2 { get { return null; } } public object Property3 { set { } } public object Property4 { get; set; } public object Property5 { set { } } public object Property6 { get; set; } public object Property7 { get { return null; } } //wrong by-{value,ref} return object o = null; public object Property8 { get { return null; } } public ref object Property9 { get { return ref o; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property2.set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property2.set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property3.get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property3.get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property5.get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property5.get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property7.set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property7.set").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.Property8'. 'Class.Property8' cannot implement 'Interface.Property8' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Property8", "Class.Property8").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.Property9'. 'Class.Property9' cannot implement 'Interface.Property9' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Property9", "Class.Property9").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property1' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property1").WithLocation(17, 15)); } [Fact] public void TestNoImplementationOfInterfaceIndexer() { var text = @" interface Interface { object this[int w, int x, int y, string z] { get; set; } object this[int w, int x, string y, int z] { get; set; } object this[int w, int x, string y, string z] { get; set; } object this[int w, string x, int y, int z] { get; } object this[int w, string x, int y, string z] { get; } object this[int w, string x, string y, int z] { set; } object this[int w, string x, string y, string z] { set; } ref object this[string w, int x, int y, int z] { get; } object this[string w, int x, int y, string z] { get; } } class Class : Interface { //missed first indexer entirely //wrong accessors public object this[int w, int x, string y, int z] { get { return null; } } public object this[int w, int x, string y, string z] { set { } } public object this[int w, string x, int y, int z] { get { return 0; } set { } } public object this[int w, string x, int y, string z] { set { } } public object this[int w, string x, string y, int z] { get { return 0; } set { } } public object this[int w, string x, string y, string z] { get { return null; } } // wrong by-{value,ref} return object o = null; public object this[string w, int x, int y, int z] { get { return null; } } public ref object this[string w, int x, int y, string z] { get { return ref o; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, string, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, string, string].set").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.this[string, int, int, int]'. 'Class.this[string, int, int, int]' cannot implement 'Interface.this[string, int, int, int]' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.this[string, int, int, int]", "Class.this[string, int, int, int]").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.this[string, int, int, string]'. 'Class.this[string, int, int, string]' cannot implement 'Interface.this[string, int, int, string]' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.this[string, int, int, string]", "Class.this[string, int, int, string]").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, int, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, int, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, int].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, int].set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, int, string]' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, int, string]").WithLocation(17, 15)); } [Fact] public void TestNoImplementationOfInterfaceEvent() { var text = @" interface Interface { event System.Action Event1; } class Class : Interface { //missed Event1 entirely } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 7, Column = 15 }, //1 }); } [Fact] public void TestNoImplementationOfInterfaceMethodInBase() { var text = @" interface Interface { object Method1(); object Method2(int i); } class Base : Interface { //missed Method1 entirely public object Method2(long l) { return 0; } //wrong signature } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Method2(int)' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Method2(int)").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Method1()' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Method1()").WithLocation(8, 14) ); } [Fact] public void TestNoImplementationOfBaseInterfaceMethod() { var text = @" interface Interface1 { object Method1(); } interface Interface2 { object Method2(); } class Base : Interface2 { public object Method1() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Base", "Interface2.Method2()")); } [Fact] public void TestNoImplementationOfInterfacePropertyInBase() { var text = @" interface Interface { object Property1 { get; set; } object Property2 { get; set; } } class Base : Interface { //missed Property1 entirely public long Property2 { get; set; } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.Property2'. 'Base.Property2' cannot implement 'Interface.Property2' because it does not have the matching return type of 'object'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Property2", "Base.Property2", "object").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Property1' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Property1").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.Property2'. 'Base.Property2' cannot implement 'Interface.Property2' because it does not have the matching return type of 'object'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.Property2", "Base.Property2", "object").WithLocation(18, 24) ); } [Fact] public void TestNoImplementationOfInterfaceIndexerInBase() { var text = @" interface Interface { object this[int x] { get; set; } object this[string x] { get; set; } } class Base : Interface { //missed int indexer entirely public long this[string x] { get { return 0; } set { } } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.this[string]'. 'Base.this[string]' cannot implement 'Interface.this[string]' because it does not have the matching return type of 'object'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.this[string]", "Base.this[string]", "object").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.this[int]' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.this[int]").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.this[string]'. 'Base.this[string]' cannot implement 'Interface.this[string]' because it does not have the matching return type of 'object'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.this[string]", "Base.this[string]", "object").WithLocation(18, 24) ); } [Fact] public void TestNoImplementationOfInterfaceEventInBase() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; } class Base : Interface { //missed Event1 entirely public event System.Action<int> Event2 { add { } remove { } } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.Event2'. 'Base.Event2' cannot implement 'Interface.Event2' because it does not have the matching return type of 'Action'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Event2", "Base.Event2", "System.Action").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Event1' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Event1").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.Event2'. 'Base.Event2' cannot implement 'Interface.Event2' because it does not have the matching return type of 'Action'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.Event2", "Base.Event2", "System.Action").WithLocation(18, 24) ); } [Fact] public void TestExplicitMethodImplementation() { var text = @" interface BaseInterface { void Method4(); } interface Interface : BaseInterface { void Method1(); void Method2(); } interface Interface2 { void Method1(); } class Base : Interface { void System.Object.Method1() { } //not an interface void Base.Method1() { } //not an interface void System.Int32.Method1() { } //not an interface void Interface2.Method1() { } //does not implement Interface2 void Interface.Method3() { } //not on Interface void Interface.Method4() { } //not on Interface public void Method1() { } public void Method2() { } public void Method4() { } } class Derived : Base { void Interface.Method1() { } //does not directly list Interface } class Derived2 : Base, Interface { void Interface.Method1() { } //fine void BaseInterface.Method4() { } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (20,10): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (21,10): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (22,10): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (23,10): error CS0540: 'Base.Interface2.Method1()': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Method1()", "Interface2"), // (24,20): error CS0539: 'Base.Method3()' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method3").WithArguments("Base.Method3()"), // (25,20): error CS0539: 'Base.Method4()' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method4").WithArguments("Base.Method4()"), // (34,10): error CS0540: 'Derived.Interface.Method1()': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Method1()", "Interface")); } [Fact] public void TestExplicitPropertyImplementation() { var text = @" interface BaseInterface { int Property4 { get; } } interface Interface : BaseInterface { int Property1 { set; } int Property2 { set; } } interface Interface2 { int Property1 { set; } } class Base : Interface { int System.Object.Property1 { set { } } //not an interface int Base.Property1 { set { } } //not an interface int System.Int32.Property1 { set { } } //not an interface int Interface2.Property1 { set { } } //does not implement Interface2 int Interface.Property3 { set { } } //not on Interface int Interface.Property4 { get { return 1; } } //not on Interface public int Property1 { set { } } public int Property2 { set { } } public int Property4 { get { return 0; } } } class Derived : Base { int Interface.Property1 { set { } } //does not directly list Interface } class Derived2 : Base, Interface { int Interface.Property1 { set { } } //fine int BaseInterface.Property4 { get { return 1; } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,9): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,9): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,9): error CS0540: 'Base.Interface2.Property1': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Property1", "Interface2"), // (23,19): error CS0539: 'Base.Property3' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property3").WithArguments("Base.Property3"), // (24,19): error CS0539: 'Base.Property4' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property4").WithArguments("Base.Property4"), // (33,9): error CS0540: 'Derived.Interface.Property1': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Property1", "Interface")); } [Fact] public void TestExplicitIndexerImplementation() { var text = @" interface BaseInterface { int this[string x, string y] { get; } } interface Interface : BaseInterface { int this[int x, int y] { set; } int this[int x, string y] { set; } } interface Interface2 { int this[int x, int y] { set; } } class Base : Interface { int System.Object.this[int x, int y] { set { } } //not an interface int Base.this[int x, int y] { set { } } //not an interface int System.Int32.this[int x, int y] { set { } } //not an interface int Interface2.this[int x, int y] { set { } } //does not implement Interface2 int Interface.this[string x, int y] { set { } } //not on Interface int Interface.this[string x, string y] { get { return 1; } } //not on Interface public int this[int x, int y] { set { } } public int this[int x, string y] { set { } } public int this[string x, string y] { get { return 0; } } } class Derived : Base { int Interface.this[int x, int y] { set { } } //does not directly list Interface } class Derived2 : Base, Interface { int Interface.this[int x, int y] { set { } } //fine int BaseInterface.this[string x, string y] { get { return 1; } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,9): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,9): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,9): error CS0540: 'Base.Interface2.this[int, int]': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.this[int, int]", "Interface2"), // (23,19): error CS0539: 'Base.this[string, int]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Base.this[string, int]"), // (24,19): error CS0539: 'Base.this[string, string]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Base.this[string, string]"), // (33,9): error CS0540: 'Derived.Interface.this[int, int]': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.this[int, int]", "Interface")); } [Fact] public void TestExplicitEventImplementation() { var text = @" interface BaseInterface { event System.Action Event4; } interface Interface : BaseInterface { event System.Action Event1; event System.Action Event2; } interface Interface2 { event System.Action Event1; } class Base : Interface { event System.Action System.Object.Event1 { add { } remove { } } //not an interface event System.Action Base.Event1 { add { } remove { } } //not an interface event System.Action System.Int32.Event1 { add { } remove { } } //not an interface event System.Action Interface2.Event1 { add { } remove { } } //does not implement Interface2 event System.Action Interface.Event3 { add { } remove { } } //not on Interface event System.Action Interface.Event4 { add { } remove { } } //not on Interface public event System.Action Event1 { add { } remove { } } public event System.Action Event2 { add { } remove { } } public event System.Action Event4 { add { } remove { } } } class Derived : Base { event System.Action Interface.Event1 { add { } remove { } } //does not directly list Interface } class Derived2 : Base, Interface { event System.Action Interface.Event1 { add { } remove { } } //fine event System.Action BaseInterface.Event4 { add { } remove { } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,25): error CS0538: 'object' in explicit interface declaration is not an interface // event System.Action System.Object.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,25): error CS0538: 'Base' in explicit interface declaration is not an interface // event System.Action Base.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,25): error CS0538: 'int' in explicit interface declaration is not an interface // event System.Action System.Int32.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,25): error CS0540: 'Base.Interface2.Event1': containing type does not implement interface 'Interface2' // event System.Action Interface2.Event1 { add { } remove { } } //does not implement Interface2 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Event1", "Interface2"), // (23,35): error CS0539: 'Base.Event3' in explicit interface declaration is not a member of interface // event System.Action Interface.Event3 { add { } remove { } } //not on Interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event3").WithArguments("Base.Event3"), // (24,35): error CS0539: 'Base.Event4' in explicit interface declaration is not a member of interface // event System.Action Interface.Event4 { add { } remove { } } //not on Interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event4").WithArguments("Base.Event4"), // (33,25): error CS0540: 'Derived.Interface.Event1': containing type does not implement interface 'Interface' // event System.Action Interface.Event1 { add { } remove { } } //does not directly list Interface Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Event1", "Interface")); } [Fact] public void TestExplicitMethodImplementation2() { var text = @" public interface I<T> { void F(); } public class C : I<object> { void I<dynamic>.F() { } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,10): error CS0540: 'C.I<dynamic>.F()': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.F()", "I<dynamic>") ); } [Fact] public void TestExplicitPropertyImplementation2() { var text = @" public interface I<T> { int P { set; } } public class C : I<object> { int I<dynamic>.P { set { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,9): error CS0540: 'C.I<dynamic>.P': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.P", "I<dynamic>") ); } [Fact] public void TestExplicitIndexerImplementation2() { var text = @" public interface I<T> { int this[int x] { set; } } public class C : I<object> { int I<dynamic>.this[int x] { set { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,9): error CS0540: 'C.I<dynamic>.this[int]': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.this[int]", "I<dynamic>")); } [Fact] public void TestExplicitEventImplementation2() { var text = @" public interface I<T> { event System.Action E; } public class C : I<object> { event System.Action I<dynamic>.E { add { } remove { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,25): error CS0540: 'C.I<dynamic>.E': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.E", "I<dynamic>") ); } [Fact] public void TestInterfaceImplementationMistakes() { var text = @" interface Interface { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); } partial class Base : Interface { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); }"; CreateCompilation(text).VerifyDiagnostics( // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method7()'. 'Base.Method7()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method7()", "Base.Method7()").WithLocation(13, 22), // (13,22): error CS0738: 'Base' does not implement interface member 'Interface.Method2()'. 'Base.Method2()' cannot implement 'Interface.Method2()' because it does not have the matching return type of 'void'. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Method2()", "Base.Method2()", "void").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method3()'. 'Base.Method3()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method3()", "Base.Method3()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method4()'. 'Base.Method4()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method4()", "Base.Method4()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method5()'. 'Base.Method5()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method5()", "Base.Method5()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method6()'. 'Base.Method6()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method6()", "Base.Method6()").WithLocation(13, 22), // (13,22): error CS0736: 'Base' does not implement instance interface member 'Interface.Method1()'. 'Base.Method1()' cannot implement the interface member because it is static. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "Interface").WithArguments("Base", "Interface.Method1()", "Base.Method1()").WithLocation(13, 22)); } [Fact] public void TestInterfacePropertyImplementationMistakes() { var text = @" interface Interface { long Property1 { get; set; } long Property2 { get; set; } long Property3 { get; set; } long Property4 { get; set; } long Property5 { get; set; } long Property6 { get; set; } } class Base : Interface { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceIndexerImplementationMistakes() { var text = @" interface Interface { long this[int x, int y, string z] { get; set; } long this[int x, string y, int z] { get; set; } long this[int x, string y, string z] { get; set; } long this[string x, int y, int z] { get; set; } long this[string x, int y, string z] { get; set; } long this[string x, string y, int z] { get; set; } } class Base : Interface { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 14, Column = 24 }, //indexer can't be static new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceEventImplementationMistakes() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; } class Base : Interface { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceImplementationMistakesInBase() { var text = @" interface Interface { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); } partial class Base : Interface { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } partial class Base2 { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); } class Base3 : Base2 { } class Derived : Base3, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 } }); } [Fact] public void TestInterfacePropertyImplementationMistakesInBase() { var text = @" interface Interface { long Property1 { get; set; } long Property2 { get; set; } long Property3 { get; set; } long Property4 { get; set; } long Property5 { get; set; } long Property6 { get; set; } } class Base : Interface { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, }); } [Fact] public void TestInterfaceIndexerImplementationMistakesInBase() { var text = @" interface Interface { long this[int x, int y, string z] { get; set; } long this[int x, string y, int z] { get; set; } long this[int x, string y, string z] { get; set; } long this[string x, int y, int z] { get; set; } long this[string x, int y, string z] { get; set; } long this[string x, string y, int z] { get; set; } } class Base : Interface { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 14, Column = 24 }, //indexer can't be static new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, //Base2 new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 32, Column = 24 }, //indexer can't be static }); } [Fact] public void TestInterfaceEventImplementationMistakesInBase() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; } class Base : Interface { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, }); } [Fact] public void TestNewRequired() { var text = @" interface IBase { void Method1(); } interface IDerived : IBase { void Method1(); } class Base { public int field = 1; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; public int this[int x] { get { return 0; } } } class Derived : Base { public int field = 2; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; public int this[int x] { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,10): warning CS0108: 'IDerived.Method1()' hides inherited member 'IBase.Method1()'. Use the new keyword if hiding was intended. // void Method1(); Diagnostic(ErrorCode.WRN_NewRequired, "Method1").WithArguments("IDerived.Method1()", "IBase.Method1()"), // (27,16): warning CS0108: 'Derived.field' hides inherited member 'Base.field'. Use the new keyword if hiding was intended. // public int field = 2; Diagnostic(ErrorCode.WRN_NewRequired, "field").WithArguments("Derived.field", "Base.field"), // (28,16): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property"), // (29,22): warning CS0108: 'Derived.Interface' hides inherited member 'Base.Interface'. Use the new keyword if hiding was intended. // public interface Interface { } Diagnostic(ErrorCode.WRN_NewRequired, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (30,18): warning CS0108: 'Derived.Class' hides inherited member 'Base.Class'. Use the new keyword if hiding was intended. // public class Class { } Diagnostic(ErrorCode.WRN_NewRequired, "Class").WithArguments("Derived.Class", "Base.Class"), // (31,19): warning CS0108: 'Derived.Struct' hides inherited member 'Base.Struct'. Use the new keyword if hiding was intended. // public struct Struct { } Diagnostic(ErrorCode.WRN_NewRequired, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (32,17): warning CS0108: 'Derived.Enum' hides inherited member 'Base.Enum'. Use the new keyword if hiding was intended. // public enum Enum { Element } Diagnostic(ErrorCode.WRN_NewRequired, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (33,26): warning CS0108: 'Derived.Delegate' hides inherited member 'Base.Delegate'. Use the new keyword if hiding was intended. // public delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewRequired, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (34,27): warning CS0108: 'Derived.Event' hides inherited member 'Base.Event'. Use the new keyword if hiding was intended. // public event Delegate Event; Diagnostic(ErrorCode.WRN_NewRequired, "Event").WithArguments("Derived.Event", "Base.Event"), // (35,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. // public int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]"), // (34,27): warning CS0067: The event 'Derived.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Derived.Event"), // (21,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event")); } [Fact] public void TestNewNotRequired() { var text = @" class C { //not hiding anything public new int field; public new int Property { get { return 0; } } public new interface Interface { } public new class Class { } public new struct Struct { } public new enum Enum { Element } public new delegate void Delegate(); public new event Delegate Event; public new int this[int x] { get { return 0; } } } struct S { //not hiding anything public new int field; public new int Property { get { return 0; } } public new interface Interface { } public new class Class { } public new struct Struct { } public new enum Enum { Element } public new delegate void Delegate(); public new event Delegate Event; public new int this[int x] { get { return 0; } } } interface Interface { void Method(); int Property { get; } } class D : Interface { //not required for interface impls public new void Method() { } public new int Property { get { return 0; } } } class Base : Interface { void Interface.Method() { } int Interface.Property { get { return 0; } } } class Derived : Base { //not hiding Base members because impls are explicit public new void Method() { } public new int Property { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,20): warning CS0109: The member 'C.field' does not hide an accessible member. The new keyword is not required. // public new int field; Diagnostic(ErrorCode.WRN_NewNotRequired, "field").WithArguments("C.field"), // (6,20): warning CS0109: The member 'C.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("C.Property"), // (12,31): warning CS0109: The member 'C.Event' does not hide an accessible member. The new keyword is not required. // public new event Delegate Event; Diagnostic(ErrorCode.WRN_NewNotRequired, "Event").WithArguments("C.Event"), // (7,26): warning CS0109: The member 'C.Interface' does not hide an accessible member. The new keyword is not required. // public new interface Interface { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Interface").WithArguments("C.Interface"), // (8,22): warning CS0109: The member 'C.Class' does not hide an accessible member. The new keyword is not required. // public new class Class { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Class").WithArguments("C.Class"), // (9,23): warning CS0109: The member 'C.Struct' does not hide an accessible member. The new keyword is not required. // public new struct Struct { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Struct").WithArguments("C.Struct"), // (10,21): warning CS0109: The member 'C.Enum' does not hide an accessible member. The new keyword is not required. // public new enum Enum { Element } Diagnostic(ErrorCode.WRN_NewNotRequired, "Enum").WithArguments("C.Enum"), // (11,30): warning CS0109: The member 'C.Delegate' does not hide an accessible member. The new keyword is not required. // public new delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewNotRequired, "Delegate").WithArguments("C.Delegate"), // (13,20): warning CS0109: The member 'C.this[int]' does not hide an accessible member. The new keyword is not required. // public new int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "this").WithArguments("C.this[int]"), // (19,20): warning CS0109: The member 'S.field' does not hide an accessible member. The new keyword is not required. // public new int field; Diagnostic(ErrorCode.WRN_NewNotRequired, "field").WithArguments("S.field"), // (20,20): warning CS0109: The member 'S.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("S.Property"), // (26,31): warning CS0109: The member 'S.Event' does not hide an accessible member. The new keyword is not required. // public new event Delegate Event; Diagnostic(ErrorCode.WRN_NewNotRequired, "Event").WithArguments("S.Event"), // (21,26): warning CS0109: The member 'S.Interface' does not hide an accessible member. The new keyword is not required. // public new interface Interface { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Interface").WithArguments("S.Interface"), // (22,22): warning CS0109: The member 'S.Class' does not hide an accessible member. The new keyword is not required. // public new class Class { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Class").WithArguments("S.Class"), // (23,23): warning CS0109: The member 'S.Struct' does not hide an accessible member. The new keyword is not required. // public new struct Struct { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Struct").WithArguments("S.Struct"), // (24,21): warning CS0109: The member 'S.Enum' does not hide an accessible member. The new keyword is not required. // public new enum Enum { Element } Diagnostic(ErrorCode.WRN_NewNotRequired, "Enum").WithArguments("S.Enum"), // (25,30): warning CS0109: The member 'S.Delegate' does not hide an accessible member. The new keyword is not required. // public new delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewNotRequired, "Delegate").WithArguments("S.Delegate"), // (27,20): warning CS0109: The member 'S.this[int]' does not hide an accessible member. The new keyword is not required. // public new int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "this").WithArguments("S.this[int]"), // (39,21): warning CS0109: The member 'D.Method()' does not hide an accessible member. The new keyword is not required. // public new void Method() { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("D.Method()"), // (40,20): warning CS0109: The member 'D.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("D.Property"), // (52,21): warning CS0109: The member 'Derived.Method()' does not hide an accessible member. The new keyword is not required. // public new void Method() { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived.Method()"), // (53,20): warning CS0109: The member 'Derived.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("Derived.Property"), // (5,20): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value 0 // public new int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "0"), // (26,31): warning CS0067: The event 'S.Event' is never used // public new event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("S.Event"), // (19,20): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value 0 // public new int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "0"), // (12,31): warning CS0067: The event 'C.Event' is never used // public new event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("C.Event") ); } [Fact] public void TestNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); //for virtual case in Derived public virtual void Method4() { } public virtual void Method5() { } public virtual void Method6() { } //for override case in Derived2 public virtual void Method7() { } public virtual void Method8() { } public virtual void Method9() { } //for grandparent case in Derived2 public virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } } abstract class Derived : Base { //abstract -> * public void Method1() { } public abstract void Method2(); public virtual void Method3() { } //virtual -> * public void Method4() { } public abstract void Method5(); public virtual void Method6() { } //for override case in Derived2 public override void Method7() { } public override void Method8() { } public override void Method9() { } } abstract class Derived2 : Derived { //override -> * public void Method7() { } public abstract void Method8(); public virtual void Method9() { } //grandparent case public void Method10() { } public abstract void Method11(); public virtual void Method12() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, }); } [Fact] public void TestPropertyNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract long Property1 { get; set; } public abstract long Property2 { get; set; } public abstract long Property3 { get; set; } //for virtual case in Derived public virtual long Property4 { get; set; } public virtual long Property5 { get; set; } public virtual long Property6 { get; set; } //for override case in Derived2 public virtual long Property7 { get; set; } public virtual long Property8 { get; set; } public virtual long Property9 { get; set; } //for grandparent case in Derived2 public virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } } abstract class Derived : Base { //abstract -> * public long Property1 { get; set; } public abstract long Property2 { get; set; } public virtual long Property3 { get; set; } //virtual -> * public long Property4 { get; set; } public abstract long Property5 { get; set; } public virtual long Property6 { get; set; } //for override case in Derived2 public override long Property7 { get; set; } public override long Property8 { get; set; } public override long Property9 { get; set; } } abstract class Derived2 : Derived { //override -> * public long Property7 { get; set; } public abstract long Property8 { get; set; } public virtual long Property9 { get; set; } //grandparent case public long Property10 { get; set; } public abstract long Property11 { get; set; } public virtual long Property12 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, //1.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, //2.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, //3.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, //4 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, //5 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, //6 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, //7 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, //8 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, //9 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, //10 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, //11 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, //12 }); } [Fact] public void TestIndexerNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract long this[int w, int x, int y, string z] { get; set; } public abstract long this[int w, int x, string y, int z] { get; set; } public abstract long this[int w, int x, string y, string z] { get; set; } //for virtual case in Derived public virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } public virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } //for override case in Derived2 public virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } //for grandparent case in Derived2 public virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } } abstract class Derived : Base { //abstract -> * public long this[int w, int x, int y, string z] { get { return 0; } set { } } public abstract long this[int w, int x, string y, int z] { get; set; } public virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } //virtual -> * public long this[int w, string x, int y, int z] { get { return 0; } set { } } public abstract long this[int w, string x, int y, string z] { get; set; } public virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } //for override case in Derived2 public override long this[int w, string x, string y, string z] { get { return 0; } set { } } public override long this[string w, int x, int y, int z] { get { return 0; } set { } } public override long this[string w, int x, int y, string z] { get { return 0; } set { } } } abstract class Derived2 : Derived { //override -> * public long this[int w, string x, string y, string z] { get { return 0; } set { } } public abstract long this[string w, int x, int y, int z] { get; set; } public virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } //grandparent case public long this[string w, int x, string y, int z] { get { return 0; } set { } } public abstract long this[string w, int x, string y, string z] { get; set; } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, //1.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, //2.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, //3.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, //4 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, //5 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, //6 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, //7 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, //8 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, //9 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, //10 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, //11 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, //12 }); } [Fact] public void TestEventNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; //for virtual case in Derived public virtual event System.Action Event4 { add { } remove { } } public virtual event System.Action Event5 { add { } remove { } } public virtual event System.Action Event6 { add { } remove { } } //for override case in Derived2 public virtual event System.Action Event7 { add { } remove { } } public virtual event System.Action Event8 { add { } remove { } } public virtual event System.Action Event9 { add { } remove { } } //for grandparent case in Derived2 public virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } } abstract class Derived : Base { //abstract -> * public event System.Action Event1 { add { } remove { } } public abstract event System.Action Event2; public virtual event System.Action Event3 { add { } remove { } } //virtual -> * public event System.Action Event4 { add { } remove { } } public abstract event System.Action Event5; public virtual event System.Action Event6 { add { } remove { } } //for override case in Derived2 public override event System.Action Event7 { add { } remove { } } public override event System.Action Event8 { add { } remove { } } public override event System.Action Event9 { add { } remove { } } } abstract class Derived2 : Derived { //override -> * public event System.Action Event7 { add { } remove { } } public abstract event System.Action Event8; public virtual event System.Action Event9 { add { } remove { } } //grandparent case public event System.Action Event10 { add { } remove { } } public abstract event System.Action Event11; public virtual event System.Action Event12 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (28,32): error CS0533: 'Derived.Event1' hides inherited abstract member 'Base.Event1' // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event1").WithArguments("Derived.Event1", "Base.Event1"), // (28,32): warning CS0114: 'Derived.Event1' hides inherited member 'Base.Event1'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event1").WithArguments("Derived.Event1", "Base.Event1"), // (29,41): error CS0533: 'Derived.Event2' hides inherited abstract member 'Base.Event2' // public abstract event System.Action Event2; Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (29,41): warning CS0114: 'Derived.Event2' hides inherited member 'Base.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event2; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (30,40): error CS0533: 'Derived.Event3' hides inherited abstract member 'Base.Event3' // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event3").WithArguments("Derived.Event3", "Base.Event3"), // (30,40): warning CS0114: 'Derived.Event3' hides inherited member 'Base.Event3'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event3").WithArguments("Derived.Event3", "Base.Event3"), // (33,32): warning CS0114: 'Derived.Event4' hides inherited member 'Base.Event4'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event4 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event4").WithArguments("Derived.Event4", "Base.Event4"), // (34,41): warning CS0114: 'Derived.Event5' hides inherited member 'Base.Event5'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event5; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event5").WithArguments("Derived.Event5", "Base.Event5"), // (35,40): warning CS0114: 'Derived.Event6' hides inherited member 'Base.Event6'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event6 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event6").WithArguments("Derived.Event6", "Base.Event6"), // (46,32): warning CS0114: 'Derived2.Event7' hides inherited member 'Derived.Event7'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event7 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event7").WithArguments("Derived2.Event7", "Derived.Event7"), // (47,41): warning CS0114: 'Derived2.Event8' hides inherited member 'Derived.Event8'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event8; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event8").WithArguments("Derived2.Event8", "Derived.Event8"), // (48,40): warning CS0114: 'Derived2.Event9' hides inherited member 'Derived.Event9'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event9 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event9").WithArguments("Derived2.Event9", "Derived.Event9"), // (51,32): warning CS0114: 'Derived2.Event10' hides inherited member 'Base.Event10'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event10 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event10").WithArguments("Derived2.Event10", "Base.Event10"), // (52,41): warning CS0114: 'Derived2.Event11' hides inherited member 'Base.Event11'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event11; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event11").WithArguments("Derived2.Event11", "Base.Event11"), // (53,40): warning CS0114: 'Derived2.Event12' hides inherited member 'Base.Event12'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event12 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event12").WithArguments("Derived2.Event12", "Base.Event12")); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod() { var text = @" public interface Interface<T> { void Method(int i); void Method(T i); } public class Class : Interface<int> { void Interface<int>.Method(int i) { } //this explicitly implements both methods in Interface<int> public void Method(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 10, Column = 25, IsWarning = true }, }); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethodWithDifferingConstraints() { var text = @" public interface Interface<T> { void Method<V>(int i) where V : new(); void Method<V>(T i); } public class Class : Interface<int> { void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): warning CS0473: Explicit interface implementation 'Class.Interface<int>.Method<V>(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<int>.Method<V>(int)").WithLocation(10, 25)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethodWithDifferingConstraints_OppositeDeclarationOrder() { var text = @" public interface Interface<T> { void Method<V>(T i); void Method<V>(int i) where V : new(); } public class Class : Interface<int> { void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): warning CS0473: Explicit interface implementation 'Class.Interface<int>.Method<V>(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<int>.Method<V>(int)").WithLocation(10, 25), // (10,48): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(10, 48), // (11,17): error CS0425: The constraints for type parameter 'V' of method 'Class.Method<V>(int)' must match the constraints for type parameter 'V' of interface method 'Interface<int>.Method<V>(int)'. Consider using an explicit interface implementation instead. // public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Method").WithArguments("V", "Class.Method<V>(int)", "V", "Interface<int>.Method<V>(int)").WithLocation(11, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceIndexer() { var text = @" public interface Interface<T> { long this[int i] { set; } long this[T i] { set; } } public class Class : Interface<int> { long Interface<int>.this[int i] { set { } } //this explicitly implements both methods in Interface<int> public long this[int i] { set { } } //this is here to avoid CS0535 - not implementing interface method } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 10, Column = 25, IsWarning = true }, }); } [Fact] public void TestAmbiguousImplementationMethod() { var text = @" public interface Interface<T, U> { void Method(int i); void Method(T i); void Method(U i); } public class Base<T> : Interface<T, T> { public void Method(int i) { } public void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class Other : Interface<int, int> { void Interface<int, int>.Method(int i) { } } class YetAnother : Interface<int, int> { public void Method(int i) { } } "; //Both Base methods implement Interface.Method(int) //Both Base methods implement Interface.Method(T) //Both Base methods implement Interface.Method(U) CreateCompilation(text).VerifyDiagnostics( // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (19,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(19, 15), // (19,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(19, 15), // (21,30): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(21, 30) ); } [Fact] public void TestAmbiguousImplementationIndexer() { var text = @" public interface Interface<T, U> { long this[int i] { set; } long this[T i] { set; } long this[U i] { set; } } public class Base<T> : Interface<T, T> { public long this[int i] { set { } } public long this[T i] { set { } } } public class Derived : Base<int>, Interface<int, int> { } "; // CONSIDER: Dev10 doesn't report these warnings - not sure why CreateCompilation(text).VerifyDiagnostics( // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35)); } [Fact] public void TestHideAmbiguousImplementationMethod() { var text = @" public interface Interface<T, U> { void Method(int i); void Method(T i); void Method(U i); } public class Base<T> : Interface<T, T> { public void Method(int i) { } public void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { public new void Method(int i) { } //overrides Base's interface mapping } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousImplementationIndexer() { var text = @" public interface Interface<T, U> { long this[int i] { set; } long this[T i] { set; } long this[U i] { set; } } public class Base<T> : Interface<T, T> { public long this[int i] { set { } } public long this[T i] { set { } } } public class Derived : Base<int>, Interface<int, int> { public new long this[int i] { set { } } //overrides Base's interface mapping } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousOverridesMethod() { var text = @" public class Base<T, U> { public virtual void Method(int i) { } public virtual void Method(T i) { } public virtual void Method(U i) { } } public class Derived : Base<int, int> { public new virtual void Method(int i) { } } public class Derived2 : Derived { public override void Method(int i) { base.Method(i); } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousOverridesIndexer() { var text = @" public class Base<T, U> { public virtual long this[int i] { set { } } public virtual long this[T i] { set { } } public virtual long this[U i] { set { } } } public class Derived : Base<int, int> { public new virtual long this[int i] { set { } } } public class Derived2 : Derived { public override long this[int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestAmbiguousOverrideMethod() { var text = @" public class Base<TShort, TInt> { public virtual void Method(TShort s, int i) { } public virtual void Method(short s, TInt i) { } } public class Derived : Base<short, int> { public override void Method(short s, int i) { } } "; CSharpCompilation comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.Method(TShort, int)' and 'Base<TShort, TInt>.Method(short, TInt)' have the same signature in type 'Derived', so they cannot be overridden // public override void Method(short s, int i) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "Method").WithArguments("Base<TShort, TInt>.Method(TShort, int)", "Base<TShort, TInt>.Method(short, TInt)", "Derived").WithLocation(10, 26) ); } else { comp.VerifyDiagnostics( // (4,25): warning CS1957: Member 'Derived.Method(short, int)' overrides 'Base<short, int>.Method(short, int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Method(TShort s, int i) { } Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Method").WithArguments("Base<short, int>.Method(short, int)", "Derived.Method(short, int)").WithLocation(4, 25), // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.Method(TShort, int)' and 'Base<TShort, TInt>.Method(short, TInt)' have the same signature in type 'Derived', so they cannot be overridden // public override void Method(short s, int i) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "Method").WithArguments("Base<TShort, TInt>.Method(TShort, int)", "Base<TShort, TInt>.Method(short, TInt)", "Derived").WithLocation(10, 26) ); } } [Fact] public void TestAmbiguousOverrideIndexer() { var text = @" public class Base<TShort, TInt> { public virtual long this[TShort s, int i] { set { } } public virtual long this[short s, TInt i] { set { } } } public class Derived : Base<short, int> { public override long this[short s, int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.this[TShort, int]' and 'Base<TShort, TInt>.this[short, TInt]' have the same signature in type 'Derived', so they cannot be overridden Diagnostic(ErrorCode.ERR_AmbigOverride, "this").WithArguments("Base<TShort, TInt>.this[TShort, int]", "Base<TShort, TInt>.this[short, TInt]", "Derived")); } [Fact] public void TestRuntimeAmbiguousOverride() { var text = @" class Base<TInt> { //these signatures differ only in ref/out public virtual void Method(int @in, ref int @ref) { } public virtual void Method(TInt @in, out TInt @out) { @out = @in; } } class Derived : Base<int> { public override void Method(int @in, ref int @ref) { } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, compilation.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (compilation.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { // We no longer report a runtime ambiguous override because the compiler // produces a methodimpl record to disambiguate. compilation.VerifyDiagnostics( ); } else { compilation.VerifyDiagnostics( // (5,25): warning CS1957: Member 'Derived.Method(int, ref int)' overrides 'Base<int>.Method(int, ref int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Method(int @in, ref int @ref) { } Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Method").WithArguments("Base<int>.Method(int, ref int)", "Derived.Method(int, ref int)").WithLocation(5, 25) ); } } [Fact] public void TestOverrideInaccessibleMethod() { var text1 = @" public class Base { internal virtual void Method() {} } "; var text2 = @" public class Derived : Base { internal override void Method() { } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleProperty() { var text1 = @" public class Base { internal virtual long Property { get; set; } } "; var text2 = @" public class Derived : Base { internal override long Property { get; set; } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleIndexer() { var text1 = @" public class Base { internal virtual long this[int x] { get { return 0; } set { } } } "; var text2 = @" public class Derived : Base { internal override long this[int x] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleEvent() { var text1 = @" public class Base { internal virtual event System.Action Event { add { } remove { } } } "; var text2 = @" public class Derived : Base { internal override event System.Action Event { add { } remove { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 43 }, //can't see internal method in other compilation }); } [Fact] public void TestVirtualMethodAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual void Method1() { } internal virtual void Method2() { } internal virtual void Method3() { } protected virtual void Method4() { } protected virtual void Method5() { } protected virtual void Method6() { } protected internal virtual void Method7() { } protected internal virtual void Method8() { } protected internal virtual void Method9() { } protected internal virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } public virtual void Method13() { } private protected virtual void Method14() { } private protected virtual void Method15() { } private protected virtual void Method16() { } private protected virtual void Method17() { } } public class Derived1 : Base { protected override void Method1() { } protected internal override void Method2() { } public override void Method3() { } internal override void Method4() { } protected internal override void Method5() { } public override void Method6() { } internal override void Method7() { } protected override void Method8() { } protected internal override void Method9() { } //correct public override void Method10() { } internal override void Method11() { } protected override void Method12() { } protected internal override void Method13() { } internal override void Method14() { } protected override void Method15() { } protected internal override void Method16() { } public override void Method17() { } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (30,38): error CS0507: 'Derived1.Method2()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method2()' // protected internal override void Method2() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method2").WithArguments("Derived1.Method2()", "internal", "Base.Method2()").WithLocation(30, 38), // (31,26): error CS0507: 'Derived1.Method3()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method3()' // public override void Method3() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method3").WithArguments("Derived1.Method3()", "internal", "Base.Method3()").WithLocation(31, 26), // (33,28): error CS0507: 'Derived1.Method4()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method4()' // internal override void Method4() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method4").WithArguments("Derived1.Method4()", "protected", "Base.Method4()").WithLocation(33, 28), // (34,38): error CS0507: 'Derived1.Method5()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method5()' // protected internal override void Method5() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method5").WithArguments("Derived1.Method5()", "protected", "Base.Method5()").WithLocation(34, 38), // (35,26): error CS0507: 'Derived1.Method6()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method6()' // public override void Method6() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method6").WithArguments("Derived1.Method6()", "protected", "Base.Method6()").WithLocation(35, 26), // (37,28): error CS0507: 'Derived1.Method7()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method7()' // internal override void Method7() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method7").WithArguments("Derived1.Method7()", "protected internal", "Base.Method7()").WithLocation(37, 28), // (38,29): error CS0507: 'Derived1.Method8()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method8()' // protected override void Method8() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method8").WithArguments("Derived1.Method8()", "protected internal", "Base.Method8()").WithLocation(38, 29), // (40,26): error CS0507: 'Derived1.Method10()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method10()' // public override void Method10() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method10").WithArguments("Derived1.Method10()", "protected internal", "Base.Method10()").WithLocation(40, 26), // (42,28): error CS0507: 'Derived1.Method11()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method11()' // internal override void Method11() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method11").WithArguments("Derived1.Method11()", "public", "Base.Method11()").WithLocation(42, 28), // (43,29): error CS0507: 'Derived1.Method12()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method12()' // protected override void Method12() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method12").WithArguments("Derived1.Method12()", "public", "Base.Method12()").WithLocation(43, 29), // (44,38): error CS0507: 'Derived1.Method13()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method13()' // protected internal override void Method13() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method13").WithArguments("Derived1.Method13()", "public", "Base.Method13()").WithLocation(44, 38), // (46,28): error CS0507: 'Derived1.Method14()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method14()' // internal override void Method14() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method14").WithArguments("Derived1.Method14()", "private protected", "Base.Method14()").WithLocation(46, 28), // (47,29): error CS0507: 'Derived1.Method15()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method15()' // protected override void Method15() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method15").WithArguments("Derived1.Method15()", "private protected", "Base.Method15()").WithLocation(47, 29), // (48,38): error CS0507: 'Derived1.Method16()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method16()' // protected internal override void Method16() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method16").WithArguments("Derived1.Method16()", "private protected", "Base.Method16()").WithLocation(48, 38), // (49,26): error CS0507: 'Derived1.Method17()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method17()' // public override void Method17() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method17").WithArguments("Derived1.Method17()", "private protected", "Base.Method17()").WithLocation(49, 26), // (29,29): error CS0507: 'Derived1.Method1()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method1()' // protected override void Method1() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method1").WithArguments("Derived1.Method1()", "internal", "Base.Method1()").WithLocation(29, 29) ); } [Fact] public void TestVirtualPropertyAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual long Property1 { get; set; } internal virtual long Property2 { get; set; } internal virtual long Property3 { get; set; } protected virtual long Property4 { get; set; } protected virtual long Property5 { get; set; } protected virtual long Property6 { get; set; } protected internal virtual long Property7 { get; set; } protected internal virtual long Property8 { get; set; } protected internal virtual long Property9 { get; set; } protected internal virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } public virtual long Property13 { get; set; } } public class Derived1 : Base { protected override long Property1 { get; set; } protected internal override long Property2 { get; set; } public override long Property3 { get; set; } internal override long Property4 { get; set; } protected internal override long Property5 { get; set; } public override long Property6 { get; set; } internal override long Property7 { get; set; } protected override long Property8 { get; set; } protected internal override long Property9 { get; set; } //correct public override long Property10 { get; set; } internal override long Property11 { get; set; } protected override long Property12 { get; set; } protected internal override long Property13 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 38 }, }); } [Fact] public void TestVirtualIndexerAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual long this[int w, int x, int y, string z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, int z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } protected internal virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, string z] { get { return 0; } set { } } } public class Derived1 : Base { protected override long this[int w, int x, int y, string z] { get { return 0; } set { } } protected internal override long this[int w, int x, string y, int z] { get { return 0; } set { } } public override long this[int w, int x, string y, string z] { get { return 0; } set { } } internal override long this[int w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[int w, string x, int y, string z] { get { return 0; } set { } } public override long this[int w, string x, string y, int z] { get { return 0; } set { } } internal override long this[int w, string x, string y, string z] { get { return 0; } set { } } protected override long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, int x, int y, string z] { get { return 0; } set { } } //correct public override long this[string w, int x, string y, int z] { get { return 0; } set { } } internal override long this[string w, int x, string y, string z] { get { return 0; } set { } } protected override long this[string w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 38 }, }); } [Fact] public void TestVirtualEventAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual event System.Action Event1 { add { } remove { } } internal virtual event System.Action Event2 { add { } remove { } } internal virtual event System.Action Event3 { add { } remove { } } protected virtual event System.Action Event4 { add { } remove { } } protected virtual event System.Action Event5 { add { } remove { } } protected virtual event System.Action Event6 { add { } remove { } } protected internal virtual event System.Action Event7 { add { } remove { } } protected internal virtual event System.Action Event8 { add { } remove { } } protected internal virtual event System.Action Event9 { add { } remove { } } protected internal virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } public virtual event System.Action Event13 { add { } remove { } } } public class Derived1 : Base { protected override event System.Action Event1 { add { } remove { } } protected internal override event System.Action Event2 { add { } remove { } } public override event System.Action Event3 { add { } remove { } } internal override event System.Action Event4 { add { } remove { } } protected internal override event System.Action Event5 { add { } remove { } } public override event System.Action Event6 { add { } remove { } } internal override event System.Action Event7 { add { } remove { } } protected override event System.Action Event8 { add { } remove { } } protected internal override event System.Action Event9 { add { } remove { } } //correct public override event System.Action Event10 { add { } remove { } } internal override event System.Action Event11 { add { } remove { } } protected override event System.Action Event12 { add { } remove { } } protected internal override event System.Action Event13 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 53 }, }); } [WorkItem(540185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540185")] [Fact] public void TestChangeVirtualPropertyAccessorAccessibilityWithinAssembly() { var text = @" public class Base { public virtual long Property1 { get; protected set; } } public class Derived1 : Base { public override long Property1 { get; private set; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "set").WithArguments("Derived1.Property1.set", "protected", "Base.Property1.set")); } [Fact] public void TestChangeVirtualIndexerAccessorAccessibilityWithinAssembly() { var text = @" public class Base { public virtual long this[int x] { get { return 0; } protected set { } } } public class Derived1 : Base { public override long this[int x] { get { return 0; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,66): error CS0507: 'Derived1.this[int].set': cannot change access modifiers when overriding 'protected' inherited member 'Base.this[int].set' Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "set").WithArguments("Derived1.this[int].set", "protected", "Base.this[int].set")); } [Fact] public void TestVirtualMethodAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual void Method1() { } internal virtual void Method2() { } internal virtual void Method3() { } protected virtual void Method4() { } protected virtual void Method5() { } protected virtual void Method6() { } protected internal virtual void Method7() { } protected internal virtual void Method8() { } protected internal virtual void Method9() { } protected internal virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } public virtual void Method13() { } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override void Method1() { } protected internal override void Method2() { } public override void Method3() { } internal override void Method4() { } protected internal override void Method5() { } public override void Method6() { } //protected internal in another assembly is protected in this one internal override void Method7() { } protected override void Method8() { } //correct protected internal override void Method9() { } public override void Method10() { } internal override void Method11() { } protected override void Method12() { } protected internal override void Method13() { } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualPropertyAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual long Property1 { get; set; } internal virtual long Property2 { get; set; } internal virtual long Property3 { get; set; } protected virtual long Property4 { get; set; } protected virtual long Property5 { get; set; } protected virtual long Property6 { get; set; } protected internal virtual long Property7 { get; set; } protected internal virtual long Property8 { get; set; } protected internal virtual long Property9 { get; set; } protected internal virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } public virtual long Property13 { get; set; } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override long Property1 { get; set; } protected internal override long Property2 { get; set; } public override long Property3 { get; set; } internal override long Property4 { get; set; } protected internal override long Property5 { get; set; } public override long Property6 { get; set; } //protected internal in another assembly is protected in this one internal override long Property7 { get; set; } protected override long Property8 { get; set; } //correct protected internal override long Property9 { get; set; } public override long Property10 { get; set; } internal override long Property11 { get; set; } protected override long Property12 { get; set; } protected internal override long Property13 { get; set; } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualIndexerAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual long this[int w, int x, int y, string z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, int z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } protected internal virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override long this[int w, int x, int y, string z] { get { return 0; } set { } } protected internal override long this[int w, int x, string y, int z] { get { return 0; } set { } } public override long this[int w, int x, string y, string z] { get { return 0; } set { } } internal override long this[int w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[int w, string x, int y, string z] { get { return 0; } set { } } public override long this[int w, string x, string y, int z] { get { return 0; } set { } } //protected internal in another assembly is protected in this one internal override long this[int w, string x, string y, string z] { get { return 0; } set { } } protected override long this[string w, int x, int y, int z] { get { return 0; } set { } } //correct protected internal override long this[string w, int x, int y, string z] { get { return 0; } set { } } public override long this[string w, int x, string y, int z] { get { return 0; } set { } } internal override long this[string w, int x, string y, string z] { get { return 0; } set { } } protected override long this[string w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualEventAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual event System.Action Event1 { add { } remove { } } internal virtual event System.Action Event2 { add { } remove { } } internal virtual event System.Action Event3 { add { } remove { } } protected virtual event System.Action Event4 { add { } remove { } } protected virtual event System.Action Event5 { add { } remove { } } protected virtual event System.Action Event6 { add { } remove { } } protected internal virtual event System.Action Event7 { add { } remove { } } protected internal virtual event System.Action Event8 { add { } remove { } } protected internal virtual event System.Action Event9 { add { } remove { } } protected internal virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } public virtual event System.Action Event13 { add { } remove { } } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override event System.Action Event1 { add { } remove { } } protected internal override event System.Action Event2 { add { } remove { } } public override event System.Action Event3 { add { } remove { } } internal override event System.Action Event4 { add { } remove { } } protected internal override event System.Action Event5 { add { } remove { } } public override event System.Action Event6 { add { } remove { } } //protected internal in another assembly is protected in this one internal override event System.Action Event7 { add { } remove { } } protected override event System.Action Event8 { add { } remove { } } //correct protected internal override event System.Action Event9 { add { } remove { } } public override event System.Action Event10 { add { } remove { } } internal override event System.Action Event11 { add { } remove { } } protected override event System.Action Event12 { add { } remove { } } protected internal override event System.Action Event13 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 53 }, }); } [Fact] public void TestExplicitPropertyChangeAccessors() { var text = @" interface Interface { int Property1 { get; set; } int Property2 { get; set; } int Property3 { get; set; } int Property4 { get; } int Property5 { get; } int Property6 { get; } int Property7 { set; } int Property8 { set; } int Property9 { set; } } class Class : Interface { int Interface.Property1 { get { return 1; } } int Interface.Property2 { set { } } int Interface.Property3 { get { return 1; } set { } } int Interface.Property4 { get { return 1; } } int Interface.Property5 { set { } } int Interface.Property6 { get { return 1; } set { } } int Interface.Property7 { get { return 1; } } int Interface.Property8 { set { } } int Interface.Property9 { get { return 1; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 19, Column = 19 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 20, Column = 19 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 24, Column = 19 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 24, Column = 31 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 25, Column = 49 }, //5 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 27, Column = 19 }, //7 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 27, Column = 31 }, //7 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 29, Column = 31 }, //9 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //7 }); } [Fact] public void TestExplicitIndexerChangeAccessors() { var text = @" interface Interface { int this[int w, int x, int y, string z] { get; set; } int this[int w, int x, string y, int z] { get; set; } int this[int w, int x, string y, string z] { get; set; } int this[int w, string x, int y, int z] { get; } int this[int w, string x, int y, string z] { get; } int this[int w, string x, string y, int z] { get; } int this[int w, string x, string y, string z] { set; } int this[string w, int x, int y, int z] { set; } int this[string w, int x, int y, string z] { set; } } class Class : Interface { int Interface.this[int w, int x, int y, string z] { get { return 1; } } int Interface.this[int w, int x, string y, int z] { set { } } int Interface.this[int w, int x, string y, string z] { get { return 1; } set { } } int Interface.this[int w, string x, int y, int z] { get { return 1; } } int Interface.this[int w, string x, int y, string z] { set { } } int Interface.this[int w, string x, string y, int z] { get { return 1; } set { } } int Interface.this[int w, string x, string y, string z] { get { return 1; } } int Interface.this[string w, int x, int y, int z] { set { } } int Interface.this[string w, int x, int y, string z] { get { return 1; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, int, int, string]' is missing accessor 'Interface.this[int, int, int, string].set' // int Interface.this[int w, int x, int y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, int, int, string]", "Interface.this[int, int, int, string].set").WithLocation(19, 19), // (20,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, int, string, int]' is missing accessor 'Interface.this[int, int, string, int].get' // int Interface.this[int w, int x, string y, int z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, int, string, int]", "Interface.this[int, int, string, int].get").WithLocation(20, 19), // (24,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, string, int, string]' is missing accessor 'Interface.this[int, string, int, string].get' // int Interface.this[int w, string x, int y, string z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, string, int, string]", "Interface.this[int, string, int, string].get").WithLocation(24, 19), // (24,60): error CS0550: 'Class.Interface.this[int, string, int, string].set' adds an accessor not found in interface member 'Interface.this[int, string, int, string]' // int Interface.this[int w, string x, int y, string z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Class.Interface.this[int, string, int, string].set", "Interface.this[int, string, int, string]").WithLocation(24, 60), // (25,78): error CS0550: 'Class.Interface.this[int, string, string, int].set' adds an accessor not found in interface member 'Interface.this[int, string, string, int]' // int Interface.this[int w, string x, string y, int z] { get { return 1; } set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Class.Interface.this[int, string, string, int].set", "Interface.this[int, string, string, int]").WithLocation(25, 78), // (27,63): error CS0550: 'Class.Interface.this[int, string, string, string].get' adds an accessor not found in interface member 'Interface.this[int, string, string, string]' // int Interface.this[int w, string x, string y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Class.Interface.this[int, string, string, string].get", "Interface.this[int, string, string, string]").WithLocation(27, 63), // (27,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, string, string, string]' is missing accessor 'Interface.this[int, string, string, string].set' // int Interface.this[int w, string x, string y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, string, string, string]", "Interface.this[int, string, string, string].set").WithLocation(27, 19), // (29,60): error CS0550: 'Class.Interface.this[string, int, int, string].get' adds an accessor not found in interface member 'Interface.this[string, int, int, string]' // int Interface.this[string w, int x, int y, string z] { get { return 1; } set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Class.Interface.this[string, int, int, string].get", "Interface.this[string, int, int, string]").WithLocation(29, 60), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, int].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, int].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, int, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, int, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, int, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, int, string].set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, string, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, string, string].set").WithLocation(17, 15)); } [WorkItem(539162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539162")] [Fact] public void TestAbstractTypeMember() { var text = @" abstract partial class ConstantValue { abstract class ConstantValueDiscriminated : ConstantValue { } class ConstantValueBad : ConstantValue { } } "; //no errors CompileAndVerifyDiagnostics(text, new ErrorDescription[0]); } [Fact] public void OverridePrivatePropertyAccessor() { var text = @" public class Base { public virtual long Property1 { get; private set; } } public class Derived1 : Base { public override long Property1 { get; private set; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "set").WithArguments("Derived1.Property1.set")); } [Fact] public void OverridePrivateIndexerAccessor() { var text = @" public class Base { public virtual long this[int x] { get { return 0; } private set { } } } public class Derived1 : Base { public override long this[int x] { get { return 0; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,66): error CS0115: 'Derived1.this[int].set': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "set").WithArguments("Derived1.this[int].set")); } [WorkItem(540221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540221")] [Fact] public void AbstractOverrideOnePropertyAccessor() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1").WithLocation(19, 9), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1").WithLocation(21, 18)); } [Fact] public void AbstractOverrideOneIndexerAccessor() { var text = @" public class Base1 { public virtual long this[long x] { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long this[long x] { get; } void test1() { this[0] += 1; } } public class Derived : Base2 { public override long this[long x] { get { return 1; } set { } } void test2() { base[0]++; base[0] = 2; long x = base[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.this[long]' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base[0]").WithArguments("Base2.this[long]").WithLocation(19, 9), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.this[long]' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base[0]").WithArguments("Base2.this[long]").WithLocation(21, 18)); } [Fact] public void TestHidingErrors() { // Tests: // Hide base virtual member using new // By default members should be hidden by signature if new is not specified // new should hide by signature var text = @" using System.Collections.Generic; class Base<T> { public virtual void Method() { } public virtual void Method(T x) { } public virtual void Method(T x, T y, List<T> a, Dictionary<T, T> b) { } public virtual void Method<U>(T x, T y) { } public virtual void Method<U>(U x, T y, List<U> a, Dictionary<T, U> b) { } public virtual int Property1 { get { return 0; } } public virtual int Property2 { get { return 0; } set { } } public virtual void Method2() { } public virtual void Method3() { } } class Derived<U> : Base<U> { public void Method(U x, U y) { } public new void Method(U x, U y, List<U> a, Dictionary<U, U> b) { } public new void Method<V>(V x, U y, List<V> a, Dictionary<U, V> b) { } public void Method<V>(V x, U y, List<V> a, Dictionary<V, U> b) { } public new virtual int Property1 { set { } } public new static int Property2 { get; set; } public new static void Method(U i) { } public new class Method2 { } public void Method<A, B>(U x, U y) { } public new int Method3 { get; set; } } class Derived2 : Derived<int> { public override void Method() { } public override void Method(int i) { } public override void Method(int x, int y, List<int> a, Dictionary<int, int> b) { } public override void Method<V>(V x, int y, List<V> a, Dictionary<int, V> b) { } public override void Method<U>(int x, int y) { } public override int Property1 { get { return 1; } } public override int Property2 { get; set; } public override void Method2() { } public override void Method3() { } } class Test { public static void Main() { Derived2 d2 = new Derived2(); Derived<int> d = d2; Base<int> b = d2; b.Method(); b.Method(1); b.Method<int>(1, 1); b.Method<int>(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method2(); int x = b.Property1; b.Property2 -= 1; b.Method3(); d.Method(); Derived<int>.Method(1); d.Method<int>(1, 1); d.Method<long>(1, 1, new List<long>(), new Dictionary<int, long>()); d.Method<long>(1, 1, new List<long>(), new Dictionary<long, int>()); d.Method(1, 1, new List<int>(), new Dictionary<int, int>()); d.Method2(); d.Method<int, int>(1, 1); Derived<int>.Method2 y = new Derived<int>.Method2(); // Both Method2's are visible? d.Property1 = 1; Derived<int>.Property2 = Derived<int>.Property2; d.Method3(); x = d.Method3; } }"; CreateCompilation(text).VerifyDiagnostics( // (31,26): error CS0506: 'Derived2.Method(int)': cannot override inherited member 'Derived<int>.Method(int)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method(int)", "Derived<int>.Method(int)"), // (32,26): error CS0506: 'Derived2.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)': cannot override inherited member 'Derived<int>.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)", "Derived<int>.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)"), // (33,26): error CS0506: 'Derived2.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)': cannot override inherited member 'Derived<int>.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)", "Derived<int>.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)"), // (35,37): error CS0545: 'Derived2.Property1.get': cannot override because 'Derived<int>.Property1' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived2.Property1.get", "Derived<int>.Property1"), // (36,25): error CS0506: 'Derived2.Property2': cannot override inherited member 'Derived<int>.Property2' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Property2").WithArguments("Derived2.Property2", "Derived<int>.Property2"), // (37,26): error CS0505: 'Derived2.Method2()': cannot override because 'Derived<int>.Method2' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method2").WithArguments("Derived2.Method2()", "Derived<int>.Method2"), // (38,26): error CS0505: 'Derived2.Method3()': cannot override because 'Derived<int>.Method3' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method3").WithArguments("Derived2.Method3()", "Derived<int>.Method3")); } [Fact] public void TestOverloadingByRefOut() { var text = @" using System; abstract class Base { public abstract void Method(int x, ref int y, out Exception z); } abstract class Base2 : Base { public abstract void Method(int x, out int y, ref Exception z); // No warnings about hiding } class Derived2 : Base2 { public override void Method(int x, out int y, ref Exception z) { y = 0; } public override void Method(int x, ref int y, out Exception z) { z = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (14,26): error CS0663: 'Derived2' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public override void Method(int x, ref int y, out Exception z) { z = null; } Diagnostic(ErrorCode.ERR_OverloadRefKind, "Method").WithArguments("Derived2", "method", "ref", "out").WithLocation(14, 26)); } [Fact] public void TestOverloadingByParams() { var text = @" using System; abstract class Base { public abstract void Method(int x, params Exception[] z); public abstract void Method(int x, int[] z); } abstract class Base2 : Base { public abstract void Method(int x, Exception[] z); public abstract void Method(int x, params int[] z); }"; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0533: 'Base2.Method(int, System.Exception[])' hides inherited abstract member 'Base.Method(int, params System.Exception[])' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Method").WithArguments("Base2.Method(int, System.Exception[])", "Base.Method(int, params System.Exception[])"), // (10,26): warning CS0114: 'Base2.Method(int, System.Exception[])' hides inherited member 'Base.Method(int, params System.Exception[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Base2.Method(int, System.Exception[])", "Base.Method(int, params System.Exception[])"), // (11,26): error CS0533: 'Base2.Method(int, params int[])' hides inherited abstract member 'Base.Method(int, int[])' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Method").WithArguments("Base2.Method(int, params int[])", "Base.Method(int, int[])"), // (11,26): warning CS0114: 'Base2.Method(int, params int[])' hides inherited member 'Base.Method(int, int[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Base2.Method(int, params int[])", "Base.Method(int, int[])")); } [Fact] public void TestOverridingOmitLessAccessibleAccessor() { var text = @" using System.Collections.Generic; abstract class Base<T> { public abstract List<T> Property1 { get; internal set; } public abstract List<T> Property2 { set; internal get; } } abstract class Base2<T> : Base<T> { } class Derived : Base2<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; CreateCompilation(text).VerifyDiagnostics( // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property2.get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property2.get"), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property1.set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property1.set")); } [Fact] public void TestOverridingOmitInaccessibleAccessorInDifferentAssembly() { var text1 = @" using System; using System.Collections.Generic; public abstract class Base<T> { public abstract List<T> Property1 { get; internal set; } public abstract List<T> Property2 { set; internal get; } }"; var comp1 = CreateCompilation(text1); var text2 = @" using System.Collections.Generic; abstract class Base2<T> : Base<T> { } class Derived : Base2<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; CreateCompilation(text2, new[] { new CSharpCompilationReference(comp1) }).VerifyDiagnostics( // (10,38): error CS0546: 'Derived.Property1': cannot override because 'Base<int>.Property1' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "Property1").WithArguments("Derived.Property1", "Base<int>.Property1"), // (11,38): error CS0545: 'Derived.Property2': cannot override because 'Base<int>.Property2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "Property2").WithArguments("Derived.Property2", "Base<int>.Property2"), // (8,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property1.set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property1.set"), // (8,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property2.get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property2.get")); } [Fact] public void TestEmitSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System; using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get; set; } public virtual List<T> Property2 { set { } get { return null; } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } } class Derived2 : Derived { public override List<int> Property1 { set { } } public override List<int> Property2 { get { return null; } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics( // (11,31): error CS0239: 'Derived2.Property1': cannot override inherited member 'Derived.Property1' because it is sealed Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Property1").WithArguments("Derived2.Property1", "Derived.Property1"), // (12,31): error CS0239: 'Derived2.Property2': cannot override inherited member 'Derived.Property2' because it is sealed Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Property2").WithArguments("Derived2.Property2", "Derived.Property2")); } [Fact] public void TestOverrideAndHide() { // Tests: // Sanity check - within the same type declare members that respectively hide and override // a base virtual / abstract member var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual void Method<U>(T x) { } public abstract int Property { set; } } class Derived : Base<List<int>> { public override void Method<U>(List<int> x) { } public new void Method<U>(List<int> x) { } public override int Property { set { } } public new int Property { set{ } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,21): error CS0111: Type 'Derived' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Derived"), // (13,20): error CS0102: The type 'Derived' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Derived", "Property")); } [Fact] public void TestHidingByGenericArity() { // Tests: // Hide base virtual / abstract member with a nested type that has same name but different generic arity // Member should be available for overriding in further derived type var source = @" using System.Collections.Generic; class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { new class Method { } // Warning: new not required new class Property { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } } class NS2 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method { } public new class Property { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } // Error: can't override a type } } class NS3 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T> { } // Warning: new required public new class Property<T> { } // Warning: new not required } class Derived : Base2 { public override void Method<U>(List<int> x) { } // Error: can't override a type public override int Property { set { } } } } class NS4 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T, U> { } public class Property<T, U> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,19): warning CS0109: The member 'NS1.Base2.Method' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("NS1.Base2.Method"), // (35,30): error CS0505: 'NS2.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS2.Base2.Method' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS2.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS2.Base2.Method"), // (36,29): error CS0544: 'NS2.Derived.Property': cannot override because 'NS2.Base2.Property' is not a property Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Property").WithArguments("NS2.Derived.Property", "NS2.Base2.Property"), // (48,22): warning CS0108: 'NS3.Base2.Method<T>' hides inherited member 'NS3.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("NS3.Base2.Method<T>", "NS3.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)"), // (49,26): warning CS0109: The member 'NS3.Base2.Property<T>' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("NS3.Base2.Property<T>"), // (53,30): error CS0505: 'NS3.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS3.Base2.Method<T>' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS3.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS3.Base2.Method<T>")); } [WorkItem(540348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540348")] [Fact] public void TestOverridingBrokenTypes() { var text = @" using System.Collections.Generic; partial class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T> { } public new class Property<T> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } } partial class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T, U> { } public class Property<T, U> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } }"; // TODO: Dev10 reports fewer cascading errors CreateCompilation(text).VerifyDiagnostics( // (24,20): error CS0102: The type 'NS1' already contains a definition for 'Base' // abstract class Base<T> Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Base").WithArguments("NS1", "Base"), // (29,11): error CS0102: The type 'NS1' already contains a definition for 'Base2' // class Base2 : Base<List<int>> Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Base2").WithArguments("NS1", "Base2"), // (34,11): error CS0102: The type 'NS1' already contains a definition for 'Derived' // class Derived : Base2 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Derived").WithArguments("NS1", "Derived"), // (36,30): error CS0505: 'NS1.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS1.Base2.Method<T>' is not a function // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS1.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS1.Base2.Method<T>"), // (19,29): error CS0462: The inherited members 'NS1.Base<T>.Property' and 'NS1.Base<T>.Property' have the same signature in type 'NS1.Derived', so they cannot be overridden // public override int Property { set { } } Diagnostic(ErrorCode.ERR_AmbigOverride, "Property").WithArguments("NS1.Base<T>.Property", "NS1.Base<T>.Property", "NS1.Derived"), // (37,29): error CS0462: The inherited members 'NS1.Base<T>.Property' and 'NS1.Base<T>.Property' have the same signature in type 'NS1.Derived', so they cannot be overridden // public override int Property { set { } } Diagnostic(ErrorCode.ERR_AmbigOverride, "Property").WithArguments("NS1.Base<T>.Property", "NS1.Base<T>.Property", "NS1.Derived"), // (18,30): error CS0505: 'NS1.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS1.Base2.Method<T>' is not a function // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS1.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS1.Base2.Method<T>"), // (36,30): error CS0111: Type 'NS1.Derived' already defines a member called 'Method' with the same parameter types // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "NS1.Derived"), // (26,29): error CS0111: Type 'NS1.Base<T>' already defines a member called 'Method' with the same parameter types // public virtual void Method<U>(T x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "NS1.Base<T>"), // (13,22): warning CS0108: 'NS1.Base2.Method<T>' hides inherited member 'NS1.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)'. Use the new keyword if hiding was intended. // public class Method<T> { } Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("NS1.Base2.Method<T>", "NS1.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)"), // (14,26): warning CS0109: The member 'NS1.Base2.Property<T>' does not hide an accessible member. The new keyword is not required. // public new class Property<T> { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("NS1.Base2.Property<T>") ); } [Fact] public void TestHidingErrorsForVirtualMembers() { // Tests: // Hide non-existent base virtual member // Hide same virtual member more than once // Hide virtual member without specifying new // Overload virtual member and also specify new var text = @" class Base { internal new virtual void Method() { } internal virtual int Property { set { } } } partial class Derived : Base { public virtual void Method() { } public new virtual int Property { set { } } } partial class Derived { internal new virtual int Property { set { } } protected new virtual void Method<T>() { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,31): warning CS0109: The member 'Base.Method()' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Base.Method()"), // (14,30): error CS0102: The type 'Derived' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Derived", "Property"), // (9,25): warning CS0114: 'Derived.Method()' hides inherited member 'Base.Method()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Derived.Method()", "Base.Method()"), // (15,32): warning CS0109: The member 'Derived.Method<T>()' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived.Method<T>()")); } [Fact] public void TestHidingErrorLocations() { var text = @" class Base { public virtual void Method() { } public virtual int Property { set { } } protected class Type { } internal int Field = 1; } class Derived : Base { public new int MethOd = 2, Method = 3, METhod = 4; void Test() { long x = MethOd = Method = METhod; } class Base2 : Base { private long Type = 5, method = 2, Field = 2, field = 8, Property = 3; void Test() { long x = Type = method = Field = field = Property; } } }"; CreateCompilation(text).VerifyDiagnostics( // (12,20): warning CS0109: The member 'Derived.MethOd' does not hide an accessible member. The new keyword is not required. // public new int MethOd = 2, Method = 3, METhod = 4; Diagnostic(ErrorCode.WRN_NewNotRequired, "MethOd").WithArguments("Derived.MethOd"), // (12,44): warning CS0109: The member 'Derived.METhod' does not hide an accessible member. The new keyword is not required. // public new int MethOd = 2, Method = 3, METhod = 4; Diagnostic(ErrorCode.WRN_NewNotRequired, "METhod").WithArguments("Derived.METhod"), // (19,22): warning CS0108: 'Derived.Base2.Type' hides inherited member 'Base.Type'. Use the new keyword if hiding was intended. // private long Type = 5, method = 2, Field = 2, Diagnostic(ErrorCode.WRN_NewRequired, "Type").WithArguments("Derived.Base2.Type", "Base.Type"), // (19,44): warning CS0108: 'Derived.Base2.Field' hides inherited member 'Base.Field'. Use the new keyword if hiding was intended. // private long Type = 5, method = 2, Field = 2, Diagnostic(ErrorCode.WRN_NewRequired, "Field").WithArguments("Derived.Base2.Field", "Base.Field"), // (20,36): warning CS0108: 'Derived.Base2.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // field = 8, Property = 3; Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Base2.Property", "Base.Property") ); } [Fact] public void ImplementInterfaceUsingSealedProperty() { var text = @" interface I1 { int Bar { get; } } class C1 { public virtual int Bar { get { return 0;} set { }} } class C2 : C1, I1 { sealed public override int Bar { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void ImplementInterfaceUsingSealedEvent() { var text = @" interface I1 { event System.Action E; } class C1 { public virtual event System.Action E; void UseEvent() { E(); } } class C2 : C1, I1 { public sealed override event System.Action E; void UseEvent() { E(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void ImplementInterfaceUsingNonVirtualEvent() { var text = @" interface I { event System.Action E; event System.Action F; event System.Action G; } class C : I { event System.Action I.E { add { } remove { } } public event System.Action F { add { } remove { } } public event System.Action G; } "; var compilation = CreateCompilation(text); // This also forces computation of IsMetadataVirtual. compilation.VerifyDiagnostics( // (12,32): warning CS0067: The event 'C.G' is never used // public event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); const int numEvents = 3; var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I"); var interfaceEvents = new EventSymbol[numEvents]; interfaceEvents[0] = @interface.GetMember<EventSymbol>("E"); interfaceEvents[1] = @interface.GetMember<EventSymbol>("F"); interfaceEvents[2] = @interface.GetMember<EventSymbol>("G"); var @class = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classEvents = new EventSymbol[numEvents]; classEvents[0] = @class.GetEvent("I.E"); classEvents[1] = @class.GetMember<EventSymbol>("F"); classEvents[2] = @class.GetMember<EventSymbol>("G"); for (int i = 0; i < numEvents; i++) { var classEvent = classEvents[i]; var interfaceEvent = interfaceEvents[i]; Assert.Equal(classEvent, @class.FindImplementationForInterfaceMember(interfaceEvent)); Assert.Equal(classEvent.AddMethod, @class.FindImplementationForInterfaceMember(interfaceEvent.AddMethod)); Assert.Equal(classEvent.RemoveMethod, @class.FindImplementationForInterfaceMember(interfaceEvent.RemoveMethod)); Assert.True(classEvent.AddMethod.IsMetadataVirtual()); Assert.True(classEvent.RemoveMethod.IsMetadataVirtual()); } } [Fact] public void TestPrivateMemberHidesVirtualMember() { var text = @" abstract public class Class1 { public virtual void Member1() { } abstract class Class2 : Class1 { new private double[] Member1 = new double[] { }; abstract class Class3 : Class2 { public override void Member1() { base.Member1(); } // Error } } abstract class Class4 : Class2 { public override void Member1() { base.Member1(); } // OK } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Member1").WithArguments("Class1.Class2.Class3.Member1()", "Class1.Class2.Member1")); } [Fact] public void ImplicitMultipleInterfaceInGrandChild() { var text = @" interface I1 { void Bar(); } interface I2 { void Bar(); } class C1 : I1 { public void Bar() { } } class C2 : C1, I1, I2 { public new void Bar() { } } "; var comp = CreateCompilation(text); var c2Type = comp.Assembly.Modules[0].GlobalNamespace.GetTypeMembers("C2").Single(); comp.VerifyDiagnostics(DiagnosticDescription.None); Assert.True(c2Type.Interfaces().All(iface => iface.Name == "I1" || iface.Name == "I2")); } [WorkItem(540451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540451")] [Fact] public void TestImplicitImplSignatureMismatches() { // Tests: // Mismatching ref / out in signature of implemented member var source = @" using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Base { public void Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Toggle ref, out - CS0535 public void Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } } class Derived : Base, I2 // Implicit implementation in base { } class Class : I2 // Implicit implementation { public void Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Omit ref, out - CS0535 public void Method<U>(int a, U[] b, List<U>[] c) { b = null; } } class Class2 : I2 // Implicit implementation { // Additional ref - CS0535 public void Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } // Additional out - CS0535 public void Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (21,7): error CS0535: 'Derived' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Derived", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (24,7): error CS0535: 'Class' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (31,7): error CS0535: 'Class2' does not implement interface member 'I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])"), // (31,7): error CS0535: 'Class2' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])")); } [Fact] public void TestExplicitImplSignatureMismatches() { // Tests: // Mismatching ref / out in signature of implemented member var source = @" using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Class1 : I1<string>, I2 { void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Toggle ref, out - CS0535 void I2.Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } } class Class : I2 { void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Omit ref, out - CS0535 void I2.Method<U>(int a, U[] b, List<U>[] c) { b = null; } } class Class2 : I2, I1<string> { // Additional ref - CS0535 void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } // Additional out - CS0535 void I2.Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS0539: 'Class.Method<U>(int, U[], System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(int a, U[] b, List<U>[] c) { b = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class.Method<U>(int, U[], System.Collections.Generic.List<U>[])"), // (17,13): error CS0539: 'Class1.Method<U>(ref int, out U[], System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class1.Method<U>(ref int, out U[], System.Collections.Generic.List<U>[])"), // (20,15): error CS0535: 'Class' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (13,28): error CS0535: 'Class1' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class1 : I1<string>, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class1", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (22,40): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (15,40): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (22,54): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (15,54): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (32,13): error CS0539: 'Class2.Method<U>(ref int, out U[], out System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method<U>(ref int, out U[], out System.Collections.Generic.List<U>[])"), // (30,21): error CS0539: 'Class2.Method(ref int, long, string, params System.Collections.Generic.List<string>[])' in explicit interface declaration is not a member of interface // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method(ref int, long, string, params System.Collections.Generic.List<string>[])"), // (27,16): error CS0535: 'Class2' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class2 : I2, I1<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (27,20): error CS0535: 'Class2' does not implement interface member 'I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])' // class Class2 : I2, I1<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<string>").WithArguments("Class2", "I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])"), // (30,44): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (30,58): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c")); } [Fact] public void TestImplicitImplSignatureMismatches2() { // Tests: // Change return type of implemented member // Change parameter types of implemented member // Change number / order of generic method type parameters in implemented method //UNDONE: type constraint mismatch var text = @" interface Interface { void Method<T>(long l, int i); } interface Interface2 { void Method<T, U, V>(T l, U i, V z); } interface Interface3 { int Property {set;} } class Class1 : Interface { public void Method<T, U>(long l, int i) { } //wrong arity } class Base2 { public void Method(long l, int i) { } //wrong arity } class Class2 : Base2, Interface { } class Base3 { public void Method<V, T, U>(T l, U i, V z) { } //wrong order } class Base31 : Base3 { } class Class3 : Base31, Interface2 { } class Class4 : Interface { public int Method<T>(long l, int i) { return 0; } //wrong return type } class Class41 : Interface3 { public long Property { set { } } //wrong return type } class Class5 : Interface { public void Method1<T>(long l, int i) { } //wrong name } class Class6 : Interface { public void Method<T>(long l) { } //wrong parameter count } class Base7 { public void Method<T>(int i, long l) { } //wrong parameter types } class Class7 : Base7, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (17,16): error CS0535: 'Class1' does not implement interface member 'Interface.Method<T>(long, int)' // class Class1 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class1", "Interface.Method<T>(long, int)").WithLocation(17, 16), // (26,23): error CS0535: 'Class2' does not implement interface member 'Interface.Method<T>(long, int)' // class Class2 : Base2, Interface { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class2", "Interface.Method<T>(long, int)").WithLocation(26, 23), // (33,24): error CS0535: 'Class3' does not implement interface member 'Interface2.Method<T, U, V>(T, U, V)' // class Class3 : Base31, Interface2 { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class3", "Interface2.Method<T, U, V>(T, U, V)").WithLocation(33, 24), // (58,23): error CS0535: 'Class7' does not implement interface member 'Interface.Method<T>(long, int)' // class Class7 : Base7, Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class7", "Interface.Method<T>(long, int)").WithLocation(58, 23), // (49,16): error CS0535: 'Class6' does not implement interface member 'Interface.Method<T>(long, int)' // class Class6 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class6", "Interface.Method<T>(long, int)").WithLocation(49, 16), // (35,16): error CS0738: 'Class4' does not implement interface member 'Interface.Method<T>(long, int)'. 'Class4.Method<T>(long, int)' cannot implement 'Interface.Method<T>(long, int)' because it does not have the matching return type of 'void'. // class Class4 : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Class4", "Interface.Method<T>(long, int)", "Class4.Method<T>(long, int)", "void").WithLocation(35, 16), // (39,17): error CS0738: 'Class41' does not implement interface member 'Interface3.Property'. 'Class41.Property' cannot implement 'Interface3.Property' because it does not have the matching return type of 'int'. // class Class41 : Interface3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface3").WithArguments("Class41", "Interface3.Property", "Class41.Property", "int").WithLocation(39, 17), // (44,16): error CS0535: 'Class5' does not implement interface member 'Interface.Method<T>(long, int)' // class Class5 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class5", "Interface.Method<T>(long, int)").WithLocation(44, 16)); } [WorkItem(540470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540470")] [Fact] public void TestExplicitImplSignatureMismatches2() { // Tests: // Change return type of implemented member // Change parameter types of implemented member // Change number / order of generic method type parameters in implemented method //UNDONE: type constraint mismatch var text = @" interface Interface { void Method<T>(long l, int i); } interface Interface2 { void Method<T, U, V>(T l, U i, V z); } interface Interface3 { int Property {set;} } class Class1 : Interface { void Interface.Method<T, U>(long l, int i) { } //wrong arity } class Class2 : Interface { void Interface.Method(long l, int i) { } //wrong arity } class Class3 : Interface2 { void Interface2.Method<V, T, U>(T l, U i, V z) { } //wrong order } class Class4 : Interface { int Interface.Method<T>(long l, int i) { return 0; } //wrong return type } class Class41 : Interface3 { long Interface3.Property { set { } } //wrong return type } class Class5 : Interface { void Interface.Method1<T>(long l, int i) { } //wrong name } class Class51 : Interface { void INterface.Method<T>(long l, int i) { } //wrong name } class Class52 : Interface, Interface2 { void Interface.Method<T, U, V>(T l, U i, V z) { } //wrong name } class Class6 : Interface { void Interface.Method<T>(long l) { } //wrong parameter count } class Class7 : Interface { void Interface.Method<T>(int i, long l) { } //wrong parameter types } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "INterface").WithArguments("INterface"), Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "INterface").WithArguments("INterface"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class1.Method<T, U>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class4.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class51", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class1", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class4", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Class41.Property"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class2", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface3").WithArguments("Class41", "Interface3.Property"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class52.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class52", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class52", "Interface2.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class7.Method<T>(int, long)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class7", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method1").WithArguments("Class5.Method1<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class3.Method<V, T, U>(T, U, V)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class5", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class3", "Interface2.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class6.Method<T>(long)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class6", "Interface.Method<T>(long, int)")); } [Fact] public void TestDuplicateImplicitImpl() { // Tests: // Implement same interface member more than once in different parts of a partial type var text = @" using System.Collections.Generic; interface I1 { int Property { set; } } abstract partial class Class : I2, I1 { abstract public int Property { set; } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } interface I2 : I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I3 { abstract public int Property { get; set; } abstract public void Method<T>(int a, ref T[] b, out List<T> c); abstract public void Method(int a = 3, params System.Exception[] b); } abstract partial class Base { abstract public int Property { set; } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } interface I3 : I2 { void Method(int a = 3, params System.Exception[] b); } abstract partial class Base { abstract public int Property { get; set; } abstract public void Method<T>(int a, ref T[] b, out List<T> c); abstract public void Method(int a = 3, params System.Exception[] b); } abstract class Derived : Base, I3, I1 { }"; CreateCompilation(text).VerifyDiagnostics( // (18,25): error CS0102: The type 'Class' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Class", "Property"), // (19,26): error CS0111: Type 'Class' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Class"), // (33,25): error CS0102: The type 'Base' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Base", "Property"), // (34,26): error CS0111: Type 'Base' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Base")); } [Fact] public void TestDuplicateExplicitImpl() { // Tests: // Implement same interface member more than once in different parts of a partial type var text = @" using System.Collections.Generic; using Type = System.Int32; interface I1 { int Property { set; } } abstract partial class Class : I2, I1 { int I1.Property { set { } } void I2.Method<U>(int a, ref U[] b, out List<U> c) { c = null; } } interface I3 : I2 { void Method(int a = 3, params System.Exception[] b); } interface I2 : I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I3 { Type I1.Property { set { } } void I2.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } void I3.Method(int a = 3, params System.Exception[] b) { } }"; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS8646: 'I2.Method<T>(int, ref T[], out List<T>)' is explicitly implemented more than once. // abstract partial class Class : I2, I1 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "Class").WithArguments("I2.Method<T>(int, ref T[], out System.Collections.Generic.List<T>)").WithLocation(8, 24), // (8,24): error CS8646: 'I1.Property' is explicitly implemented more than once. // abstract partial class Class : I2, I1 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "Class").WithArguments("I1.Property").WithLocation(8, 24), // (25,24): warning CS1066: The default value specified for parameter 'a' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I3.Method(int a = 3, params System.Exception[] b) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "a").WithArguments("a"), // (23,13): error CS0102: The type 'Class' already contains a definition for 'I1.Property' // Type I1.Property { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Class", "I1.Property"), // (24,13): error CS0111: Type 'Class' already defines a member called 'I2.Method' with the same parameter types // void I2.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("I2.Method", "Class")); } [Fact] public void TestMissingImpl() { // Tests: // For partial interfaces – test that compiler generates error if any interface methods have not been implemented // Test that compiler generates error if any interface methods have not been implemented in an abstract class var text = @" using System.Collections.Generic; partial interface I1 { int Property { set; } } abstract partial class Class : I1 { int I1.Property { set { } } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } partial interface I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I1 { void Method(int a = 3, params System.ArgumentException[] b) { } // incorrect parameter type } abstract class Base { abstract public void Method(int a = 3, params System.Exception[] b); long Property { set { } } // incorrect return type } abstract class Base2 : Base { } partial interface I1 { void Method(int a = 3, params System.Exception[] b); } abstract class Derived : Base2, I1 { void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,32): error CS0535: 'Class' does not implement interface member 'I1.Method(int, params System.Exception[])' // abstract partial class Class : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Class", "I1.Method(int, params System.Exception[])").WithLocation(7, 32), // (32,33): error CS0737: 'Derived' does not implement interface member 'I1.Property'. 'Base.Property' cannot implement an interface member because it is not public. // abstract class Derived : Base2, I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("Derived", "I1.Property", "Base.Property").WithLocation(32, 33)); } [Fact] public void TestInterfaceBaseAccessError() { // Tests: // Invoke base.InterfaceMember from within class that only inherits an interface var text = @" using System.Collections.Generic; partial interface I1 { int Property { set; } void Method<T>(int a, ref T[] b, out List<T> c); void Method(int a = 3, params System.Exception[] b); } class Class1 : I1 { public int Property { set { base.Property = value; } } public void Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } public void Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } } class Class2 : I1 { int I1.Property { set { base.Property = value; } } void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } }"; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS1066: The default value specified for parameter 'a' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "a").WithArguments("a"), // (11,38): error CS0117: 'object' does not contain a definition for 'Property' // public int Property { set { base.Property = value; } } Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property"), // (12,77): error CS0117: 'object' does not contain a definition for 'Method' // public void Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method<T>").WithArguments("object", "Method"), // (13,71): error CS0117: 'object' does not contain a definition for 'Method' // public void Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method"), // (17,34): error CS0117: 'object' does not contain a definition for 'Property' // int I1.Property { set { base.Property = value; } } Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property"), // (18,73): error CS0117: 'object' does not contain a definition for 'Method' // void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method<T>").WithArguments("object", "Method"), // (19,67): error CS0117: 'object' does not contain a definition for 'Method' // void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Implicit() { // Tests: // In signature / name of implicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<K>(T a, U[] b, List<V> c, Interface<W, K> d); } internal class Base<X, Y> { public Y Property { set { } } public void Method<V>(X A, int[] b, List<long> C, Outer<Y>.Inner<int>.Interface<Y, V> d) { } } } } internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> { public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> { public List<List<uint>> Property { get { return null; } set { } } public void Method<K>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<long>>>.Inner<List<List<T>>>.Interface<List<int>, K> D) { } public void Method<T>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<List<int>, T> D) { } } } public class Test { public static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (25,63): error CS0535: 'Derived1<U, T>' does not implement interface member 'Outer<U>.Inner<int>.Interface<long, T>.Method<K>(U, int[], System.Collections.Generic.List<long>, Outer<U>.Inner<int>.Interface<T, K>)' // internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<int>.Interface<long, T>").WithArguments("Derived1<U, T>", "Outer<U>.Inner<int>.Interface<long, T>.Method<K>(U, int[], System.Collections.Generic.List<long>, Outer<U>.Inner<int>.Interface<T, K>)").WithLocation(25, 63), // (25,63): error CS0738: 'Derived1<U, T>' does not implement interface member 'Outer<U>.Inner<int>.Interface<long, T>.Property'. 'Outer<U>.Inner<T>.Base<U, T>.Property' cannot implement 'Outer<U>.Inner<int>.Interface<long, T>.Property' because it does not have the matching return type of 'U'. // internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Outer<U>.Inner<int>.Interface<long, T>").WithArguments("Derived1<U, T>", "Outer<U>.Inner<int>.Interface<long, T>.Property", "Outer<U>.Inner<T>.Base<U, T>.Property", "U").WithLocation(25, 63), // (27,27): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'Derived1<U, T>' // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "Derived1<U, T>").WithLocation(27, 27), // (37,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'Derived1<U, T>' // public void Method<T>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<List<int>, T> D) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "Derived1<U, T>").WithLocation(37, 28), // (27,32): error CS0535: 'Derived1<U, T>.Derived2<T>' does not implement interface member 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Method<K>(System.Collections.Generic.List<System.Collections.Generic.List<int>>, System.Collections.Generic.List<System.Collections.Generic.List<T>>[], System.Collections.Generic.List<long>, Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<System.Collections.Generic.List<int>, K>)' // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>>").WithArguments("Derived1<U, T>.Derived2<T>", "Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Method<K>(System.Collections.Generic.List<System.Collections.Generic.List<int>>, System.Collections.Generic.List<System.Collections.Generic.List<T>>[], System.Collections.Generic.List<long>, Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<System.Collections.Generic.List<int>, K>)").WithLocation(27, 32), // (27,32): error CS0738: 'Derived1<U, T>.Derived2<T>' does not implement interface member 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property'. 'Derived1<U, T>.Derived2<T>.Property' cannot implement 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property' because it does not have the matching return type of 'System.Collections.Generic.List<System.Collections.Generic.List<int>>'. // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>>").WithArguments("Derived1<U, T>.Derived2<T>", "Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property", "Derived1<U, T>.Derived2<T>.Property", "System.Collections.Generic.List<System.Collections.Generic.List<int>>").WithLocation(27, 32)); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived1 : Inner<int>.Interface<ulong, string> { T Outer<T>.Inner<int>.Interface<long, string>.Property { set { } } void Inner<int>.Interface<long, string>.Method<K>(T A, int[] B, List<long> c, Dictionary<string, K> D) { } internal class Derived2<X, Y> : Outer<Y>.Inner<int>.Interface<long, X> { X Outer<X>.Inner<int>.Interface<long, Y>.Property { set { } } void Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X A, int[] b, List<long> C, Dictionary<Y, K> d) { } } } internal class Derived3 : Interface<long, string> { U Inner<U>.Interface<long, string>.Property { set { } } void Outer<T>.Inner<U>.Interface<long, string>.Method<K>(T a, K[] B, List<long> C, Dictionary<string, K> d) { } } internal class Derived4 : Outer<U>.Inner<T>.Interface<T, U> { U Outer<U>.Inner<T>.Interface<T, U>.Property { set { } } void Outer<U>.Inner<T>.Interface<T, U>.Method<K>(U a, T[] b, List<U> C, Dictionary<U, K> d) { } internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) { } internal class Derived6<u> : Outer<List<T>>.Inner<U>.Interface<List<u>, T> { List<T> Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Property { set { } } void Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Method<K>(List<T> AA, U[] b, List<List<U>> c, Dictionary<T, K> d) { } } internal class Derived7<u> : Outer<List<T>>.Inner<U>.Interface<List<U>, T> { List<u> Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Property { set { } } void Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Method<K>(List<T> AA, U[] b, List<List<u>> c, Dictionary<T, K> d) { } } } } } } class Test { public static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (48,52): error CS0539: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, K>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)"), // (57,47): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)"), // (51,39): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5' does not implement interface member 'Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<T>.Inner<U>.Interface<U, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5", "Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)"), // (72,75): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Property"), // (76,72): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, K>)"), // (70,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, Z>)"), // (70,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property"), // (62,29): error CS0540: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property': containing type does not implement interface 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>"), // (66,26): error CS0540: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, K>)': containing type does not implement interface 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, K>)", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>"), // (60,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<u>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, Z>)"), // (60,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<u>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Property"), // (14,15): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Property': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<T>.Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Property", "Outer<T>.Inner<int>.Interface<long, string>"), // (18,18): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Method<K>(T, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Method<K>(T, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)", "Outer<T>.Inner<int>.Interface<long, string>"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<ulong, string>.Method<Z>(T, int[], System.Collections.Generic.List<ulong>, System.Collections.Generic.Dictionary<string, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<ulong, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<ulong, string>.Method<Z>(T, int[], System.Collections.Generic.List<ulong>, System.Collections.Generic.Dictionary<string, Z>)"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<ulong, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<ulong, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<ulong, string>.Property"), // (23,19): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Property': containing type does not implement interface 'Outer<X>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Property", "Outer<X>.Inner<int>.Interface<long, Y>"), // (27,22): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)': containing type does not implement interface 'Outer<X>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)", "Outer<X>.Inner<int>.Interface<long, Y>"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<Y>.Inner<int>.Interface<long, X>.Method<Z>(Y, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<X, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<Y>.Inner<int>.Interface<long, X>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<Y>.Inner<int>.Interface<long, X>.Method<Z>(Y, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<X, Z>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<Y>.Inner<int>.Interface<long, X>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<Y>.Inner<int>.Interface<long, X>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<Y>.Inner<int>.Interface<long, X>.Property"), // (34,48): error CS0539: 'Outer<T>.Inner<U>.Derived3.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived3.Property"), // (38,60): error CS0539: 'Outer<T>.Inner<U>.Derived3.Method<K>(T, K[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived3.Method<K>(T, K[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)"), // (32,35): error CS0535: 'Outer<T>.Inner<U>.Derived3' does not implement interface member 'Outer<T>.Inner<U>.Interface<long, string>.Method<Z>(T, U[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived3", "Outer<T>.Inner<U>.Interface<long, string>.Method<Z>(T, U[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, Z>)"), // (32,35): error CS0535: 'Outer<T>.Inner<U>.Derived3' does not implement interface member 'Outer<T>.Inner<U>.Interface<long, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived3", "Outer<T>.Inner<U>.Interface<long, string>.Property")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_HideTypeParameter() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,67): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (10,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' // void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (10,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' // void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (17,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)' in explicit interface declaration is not a member of interface // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (14,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' in explicit interface declaration is not a member of interface // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' // internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' // internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Implicit_HideTypeParameter() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,67): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (10,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (10,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (17,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (14,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)")); } [Fact] public void TestErrorsOverridingGenericNestedClasses_HideTypeParameter() { // Tests: // In signature / name of overridden member, use generic type whose open type (C<T>) matches signature // in base class - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal abstract class Base<V, W> { internal virtual void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d) { } internal abstract void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Base<long, Y> { internal override void Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } internal override void Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (10,43): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Base<V, W>"), // (10,46): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Base<V, W>"), // (14,43): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,43): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,46): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (14,36): error CS0115: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (17,36): error CS0115: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (12,24): error CS0534: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement inherited abstract member 'Outer<X>.Inner<int>.Base<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived1").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Base<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_IncorrectPartialQualification() { // Tests: // In name of explicitly implemented member specify incorrect partially qualified type name var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived1 : Inner<int>.Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<int>.Interface<long, string>.Method<K>(T A, int[] B, List<long> c, Dictionary<string, K> D) { } internal class Derived2<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { X Inner<int>.Interface<long, Y>.Property { set { } } void Inner<long>.Interface<long, Y>.Method<K>(X A, int[] b, List<long> C, Dictionary<Y, K> d) { } } } internal class Derived3 : Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<U>.Interface<long, string>.Method<K>(T a, U[] B, List<long> C, Dictionary<string, K> d) { } } internal class Derived4 : Outer<U>.Inner<T>.Interface<T, U> { U Interface<T, U>.Property { set { } } void Inner<T>.Interface<T, U>.Method<K>(U a, T[] b, List<T> C, Dictionary<U, K> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (44,15): error CS0540: 'Outer<T>.Inner<U>.Derived4.Property': containing type does not implement interface 'Outer<T>.Inner<U>.Interface<T, U>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4.Property", "Outer<T>.Inner<U>.Interface<T, U>"), // (44,31): error CS0539: 'Outer<T>.Inner<U>.Derived4.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived4.Property"), // (48,18): error CS0540: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)': containing type does not implement interface 'Outer<T>.Inner<T>.Interface<T, U>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)", "Outer<T>.Inner<T>.Interface<T, U>"), // (48,43): error CS0539: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Property"), // (14,15): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<U>.Interface<long, string>.Property': containing type does not implement interface 'Outer<T>.Inner<U>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<U>.Interface<long, string>.Property", "Outer<T>.Inner<U>.Interface<long, string>"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<long, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<long, string>.Property"), // (23,19): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property", "Outer<T>.Inner<int>.Interface<long, Y>"), // (23,49): error CS0539: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property"), // (27,22): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)': containing type does not implement interface 'Outer<T>.Inner<long>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<long>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)", "Outer<T>.Inner<long>.Interface<long, Y>"), // (27,53): error CS0539: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<Z>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<Z>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, Z>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Property")); } [Fact] public void TestImplicitImplementationSubstitutionError() { // Tests: // Implicitly implement interface member in base generic type – the method that implements interface member // should depend on type parameter of base type to satisfy signature (return type / parameter type) equality // Test case where substitution is incorrect var source = @" using System.Collections.Generic; interface Interface { void Method(List<int> x); void Method(List<long> z); } class Base<T> { public void Method(T x) { } } class Base2<T> : Base<T> { public void Method(List<long> x) { } } class Derived : Base2<List<uint>>, Interface { } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (16,7): error CS0535: 'Derived' does not implement interface member 'Interface.Method(System.Collections.Generic.List<int>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Derived", "Interface.Method(System.Collections.Generic.List<int>)")); } [Fact] public void TestImplementAmbiguousSignaturesImplicitly_Errors() { // Tests: // Use a single member to implicitly implement // multiple base interface members that have signatures differing only by params // Implicitly implement multiple base interface members that // have signatures differing only by ref/out (some of these will be error cases) var text = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Test : I3 { public int P { get { return 0; } set { Console.WriteLine(""I1.P""); } } // public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } - Not possible to implement I3.P implicitly // public void M1(long x) { Console.WriteLine(""I1.M1""); } - Not possible to implement I1.M1 implicitly public int M1(long x) { Console.WriteLine(""I3.M1""); return 0; } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } // public void M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } - Not possible to implement I1.M6 implicitly public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } public void M7(ref long x) { Console.WriteLine(""I3.M7""); } // public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } - Not possible to implement I1.M7 implicitly public void M8(long[] x) { Console.WriteLine(""I3.M8+I1.M9""); } // Implements both I3.M8 and I1.M8 public void M9(params long[] x) { Console.WriteLine(""I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 }"; CreateCompilation(text).VerifyDiagnostics( // (32,14): error CS0738: 'Test' does not implement interface member 'I3.P'. 'Test.P' cannot implement 'I3.P' because it does not have the matching return type of 'long'. // class Test : I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I3").WithArguments("Test", "I3.P", "Test.P", "long").WithLocation(32, 14), // (32,14): error CS0738: 'Test' does not implement interface member 'I1.M1(long)'. 'Test.M1(long)' cannot implement 'I1.M1(long)' because it does not have the matching return type of 'void'. // class Test : I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I3").WithArguments("Test", "I1.M1(long)", "Test.M1(long)", "void").WithLocation(32, 14), // (32,14): error CS0535: 'Test' does not implement interface member 'I1.M6(ref long)' // class Test : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test", "I1.M6(ref long)").WithLocation(32, 14), // (32,14): error CS0535: 'Test' does not implement interface member 'I1.M7(out long)' // class Test : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test", "I1.M7(out long)").WithLocation(32, 14)); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors() { // Tests: // Implicitly / explicitly implement multiple base interface members (that have same signature) with a single member // Implicitly / explicitly implement multiple base interface members (that have same signature) with a single member from base class var source = @" using System; interface I1<T, U> { void Method<V>(T x, Func<U, T, V> v, U z); void Method<Z>(U x, Func<T, U, Z> v, T z); } class Implicit : I1<int, Int32> { public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Base { public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Base2 : Base { } class ImplicitInBase : Base2, I1<int, Int32> { } class Explicit : I1<int, Int32> { void I1<Int32, Int32>.Method<V>(int x, Func<int, int, V> v, int z) { } public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Test { public static void Main() { I1<int, int> i = new Implicit(); Func<int, int, string> x = null; i.Method<string>(1, x, 1); i = new ImplicitInBase(); i.Method<string>(1, x, 1); i = new Explicit(); i.Method<string>(1, x, 1); } }"; CreateCompilation(source).VerifyDiagnostics( // (20,27): warning CS0473: Explicit interface implementation 'Explicit.I1<int, int>.Method<V>(int, System.Func<int, int, V>, int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void I1<Int32, Int32>.Method<V>(int x, Func<int, int, V> v, int z) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Explicit.I1<int, int>.Method<V>(int, System.Func<int, int, V>, int)"), // (29,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)"), // (32,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)"), // (35,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors2() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, U v, U[] y); int Method(U x, T v, params U[] y); // Add params and change return type } class Implicit : I1<int, int> { public Action<int> Method(ref int x) { Console.WriteLine(""Method(ref int x)""); return null; } public Action<int> Method(int x) { Console.WriteLine(""Method(int x)""); return null; } public void Method(ref Func<int, int> v) { Console.WriteLine(""Method(ref Func<int, int> v)""); } // We have to implement this explicitly void I1<int, int>.Method(out Func<int, int> v) { v = null; Console.WriteLine(""I1<int, int>.Method(out Func<int, int> v)""); } public void Method(int x, int[] y) { Console.WriteLine(""Method(int x, int[] y)""); } // Implements both params and non-params version public long Method(int x, int v, int[] y) { Console.WriteLine(""Method(int x, int v, int[] y)""); return 0; } // We have to implement this explicitly int I1<int, int>.Method(int x, int v, params int[] y) { Console.WriteLine(""I1<int, int>.Method(int x, int v, params int[] y)""); return 0; } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(out System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(out System.Func<int, int>)")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors3() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, Func<T, U> v, U[] y); int Method(U x, Func<T, U> v, params U[] y); // Add params and change return type } class Base { public Action<int> Method(ref int x) { Console.WriteLine(""Method(ref int x)""); return null; } public Action<int> Method(int x) { Console.WriteLine(""Method(int x)""); return null; } public void Method(ref Func<int, int> v) { Console.WriteLine(""Method(ref Func<int, int> v)""); } public void Method(int x, int[] y) { Console.WriteLine(""Method(int x, int[] y)""); } public long Method(int x, Func<int, int> v, int[] y) { Console.WriteLine(""long Method(int x, Func<int, int> v, int[] y)""); return 0; } } class ImplicitInBase : Base, I1<int, int> { public void Method(out Func<int, int> v) { v = null; Console.WriteLine(""Method(out Func<int, int> v)""); } public int Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine(""int Method(int x, Func<int, int> v, params int[] y)""); return 0; } } class Test { public static void Main() { I1<int, int> i = new ImplicitInBase(); int x = 1; Func<int, int> y = null; i.Method(ref x); i.Method(x); i.Method(ref y); i.Method(out y); i.Method(x, new int[] { x, x, x }); i.Method(x, x, x, x); i.Method(x, y, new int[] { x, x, x }); i.Method(x, y, x, x, x); } }"; CreateCompilation(source).VerifyDiagnostics( // (25,16): warning CS0108: 'ImplicitInBase.Method(int, System.Func<int, int>, params int[])' hides inherited member 'Base.Method(int, System.Func<int, int>, int[])'. Use the new keyword if hiding was intended. // public int Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine("int Method(int x, Func<int, int> v, params int[] y)"); return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("ImplicitInBase.Method(int, System.Func<int, int>, params int[])", "Base.Method(int, System.Func<int, int>, int[])"), // (34,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method(T, U[])' and 'I1<T, U>.Method(U, params T[])' // i.Method(x, new int[] { x, x, x }); i.Method(x, x, x, x); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("I1<T, U>.Method(T, U[])", "I1<T, U>.Method(U, params T[])"), // (35,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method(T, System.Func<T, U>, U[])' and 'I1<T, U>.Method(U, System.Func<T, U>, params U[])' // i.Method(x, y, new int[] { x, x, x }); i.Method(x, y, x, x, x); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("I1<T, U>.Method(T, System.Func<T, U>, U[])", "I1<T, U>.Method(U, System.Func<T, U>, params U[])")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors4() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, Func<T, U> v, U[] y); int Method(U x, Func<T, U> v, params U[] y); // Add params and change return type } class Explicit : I1<int, int> { Action<int> I1<int, int>.Method(ref int x) { Console.WriteLine(""I1<int, int>.Method(ref int x)""); return null; } Action<int> I1<int, int>.Method(int x) { Console.WriteLine(""I1<int, int>.Method(int x)""); return null; } void I1<int, int>.Method(ref Func<int, int> v) { Console.WriteLine(""I1<int, int>.Method(ref Func<int, int> v)""); } void I1<int, int>.Method(out Func<int, int> v) { v = null; Console.WriteLine(""I1<int, int>.Method(out Func<int, int> v)""); } void I1<int, int>.Method(int x, int[] y) { Console.WriteLine(""I1<int, int>.Method(int x, int[] y)""); } // This has to be implicit so as not to clash with the above public void Method(int x, params int[] y) { Console.WriteLine(""Method(int x, params int[] y)""); } long I1<int, int>.Method(int x, Func<int, int> v, int[] y) { Console.WriteLine(""long I1<int, int>.Method(int x, Func<int, int> v, int[] y)""); return 0; } int I1<int, int>.Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine(""int I1<int, int>.Method(int x, Func<int, int> v, params int[] y)""); return 0; } } class Test { public static void Main() { I1<int, int> i = new Explicit(); int x = 1; Func<int, int> y = null; i.Method(ref x); i.Method(x); i.Method(ref y); i.Method(out y); i.Method(x, x, x, x); i.Method(x, y, x, x, x); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(ref System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(ref System.Func<int, int>)"), // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(out System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(out System.Func<int, int>)"), // (20,23): warning CS0473: Explicit interface implementation 'Explicit.I1<int, int>.Method(int, int[])' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Explicit.I1<int, int>.Method(int, int[])")); } [Fact] public void TestErrorsOverridingImplementingMember() { // Tests: // Members that implement interface members are usually marked as virtual sealed - // test the errors that are reported when trying to override these implementing members var source = @" interface I { void M(); int P { set; } } class Base : I { public void M() { } public int P { set { } } } class Derived : Base { public override void M() { } public override int P { set { } } } class Base2 { public void M() { } public int P { set { } } } class Derived2 : Base2, I { } class Derived3 : Derived2 { public override void M() { } public override int P { set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (14,26): error CS0506: 'Derived.M()': cannot override inherited member 'Base.M()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M").WithArguments("Derived.M()", "Base.M()"), // (15,25): error CS0506: 'Derived.P': cannot override inherited member 'Base.P' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("Derived.P", "Base.P"), // (27,26): error CS0506: 'Derived3.M()': cannot override inherited member 'Base2.M()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M").WithArguments("Derived3.M()", "Base2.M()"), // (28,25): error CS0506: 'Derived3.P': cannot override inherited member 'Base2.P' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("Derived3.P", "Base2.P")); } [Fact] public void TestImplementingMethodNamedFinalize() { var source = @" interface I { void Finalize(); } class C1 : I { public void Finalize() { } } class C2 : I { } class Test { public static void Main() { I i = new C1(); i.Finalize(); } }"; CreateCompilation(source).VerifyDiagnostics( // (4,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize(); Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize").WithLocation(4, 10), // (6,28): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // class C1 : I { public void Finalize() { } } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize").WithLocation(6, 28), // (7,12): error CS0737: 'C2' does not implement interface member 'I.Finalize()'. 'object.~Object()' cannot implement an interface member because it is not public. // class C2 : I { } Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I").WithArguments("C2", "I.Finalize()", "object.~Object()").WithLocation(7, 12)); } [Fact] public void TestImplementingMethodNamedFinalize2() { var source = @" interface I { int Finalize(); void Finalize(int i); } class Base { public void Finalize(int j) { } } class Derived : Base, I { public int Finalize() { return 0; } } class Test { public static void Main() { I i = new Derived(); i.Finalize(i.Finalize()); } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitMethodImplementation() { var source = @" interface T { void T<S>(); } class A<T> : global::T { void T.T<S>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (8,10): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T<S>()' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T<S>()")); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitPropertyImplementation() { var source = @" interface T { int T { get; set; } } class A<T> : global::T { int T.T { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T")); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitEventImplementation() { var source = @" interface T { event System.Action T; } class A<T> : global::T { event System.Action T.T { add { } remove { } } }"; CreateCompilation(source).VerifyDiagnostics( // (8,25): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T")); } private static CSharpCompilation CompileAndVerifyDiagnostics(string text, ErrorDescription[] expectedErrors, params CSharpCompilation[] baseCompilations) { var refs = new List<MetadataReference>(baseCompilations.Select(c => new CSharpCompilationReference(c))); var comp = CreateCompilation(text, refs); var actualErrors = comp.GetDiagnostics(); //ostensibly, we could just pass exactMatch: true to VerifyErrorCodes, but that method is short-circuited when 0 errors are expected Assert.Equal(expectedErrors.Length, actualErrors.Count()); DiagnosticsUtils.VerifyErrorCodes(actualErrors, expectedErrors); return comp; } private static CSharpCompilation CompileAndVerifyDiagnostics(string text1, string text2, ErrorDescription[] expectedErrors1, ErrorDescription[] expectedErrors2) { var comp1 = CompileAndVerifyDiagnostics(text1, expectedErrors1); var comp2 = CompileAndVerifyDiagnostics(text2, expectedErrors2, comp1); return comp2; } [Fact] [WorkItem(1016693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016693")] public void Bug1016693() { const string source = @" public class A { public virtual int P { get; set; } public class B : A { public override int P { get; set; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(31974, "https://github.com/dotnet/roslyn/issues/31974")] public void Issue31974() { const string source = @" namespace Ns1 { public interface I1<I1T1> { void M(); int P {get; set;} event System.Action E; } public class C0<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C0<I2T1, I2T2>> { } class C1<C1T1, C1T2> : I2<C1T1, C1T2> { void I1<C0<C1T1, C1T2>>.M() { } void global::Ns1.I1<C0<C1T1, C1T2>>.M() { } int I1<C0<C1T1, C1T2>>.P { get => throw null; set => throw null; } int global::Ns1.I1<C0<C1T1, C1T2>>.P { get => throw null; set => throw null; } event System.Action I1<C0<C1T1, C1T2>>.E { add => throw null; remove => throw null; } event System.Action global::Ns1.I1<C0<C1T1, C1T2>>.E { add => throw null; remove => throw null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.P' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.P").WithLocation(18, 11), // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.E' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.E").WithLocation(18, 11), // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.M()' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.M()").WithLocation(18, 11) ); } [Fact] public void DynamicMismatch_01() { var source = @" public interface I0<T> { } public interface I1 : I0<object> { } public interface I2 : I0<dynamic> { } public interface I3 : I0<object> { } public class C : I1, I2 { } public class D : I1, I3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,23): error CS1966: 'I2': cannot implement a dynamic interface 'I0<dynamic>' // public interface I2 : I0<dynamic> { } Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("I2", "I0<dynamic>").WithLocation(4, 23), // (7,14): error CS8779: 'I0<dynamic>' is already listed in the interface list on type 'C' as 'I0<object>'. // public class C : I1, I2 { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, "C").WithArguments("I0<dynamic>", "I0<object>", "C").WithLocation(7, 14) ); } [Fact] public void DynamicMismatch_02() { var source = @" public interface I0<T> { void M(); } public class C : I0<object> { void I0<object>.M(){} } public class D : C, I0<dynamic> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): error CS1966: 'D': cannot implement a dynamic interface 'I0<dynamic>' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("D", "I0<dynamic>").WithLocation(11, 21), // (11,21): error CS0535: 'D' does not implement interface member 'I0<dynamic>.M()' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0<dynamic>").WithArguments("D", "I0<dynamic>.M()").WithLocation(11, 21) ); } [Fact] public void DynamicMismatch_03() { var source = @" public interface I0<T> { void M(); } public class C : I0<object> { void I0<object>.M(){} public void M(){} } public class D : C, I0<dynamic> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,21): error CS1966: 'D': cannot implement a dynamic interface 'I0<dynamic>' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("D", "I0<dynamic>").WithLocation(12, 21), // (12,21): error CS0535: 'D' does not implement interface member 'I0<dynamic>.M()' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0<dynamic>").WithArguments("D", "I0<dynamic>.M()").WithLocation(12, 21) ); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter1() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter2() { var source = @" interface I { void Goo<T>(T?[] value) where T : struct; } class C1 : I { public void Goo<T>(T?[] value) where T : struct { } } class C2 : I { void I.Goo<T>(T?[] value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter3() { var source = @" interface I { void Goo<T>((T a, T? b)? value) where T : struct; } class C1 : I { public void Goo<T>((T a, T? b)? value) where T : struct { } } class C2 : I { void I.Goo<T>((T a, T? b)? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); var tuple = c2Goo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct1() { var source = @" interface I { T? Goo<T>() where T : struct; } class C1 : I { public T? Goo<T>() where T : struct => default; } class C2 : I { T? I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct2() { var source = @" interface I { T?[] Goo<T>() where T : struct; } class C1 : I { public T?[] Goo<T>() where T : struct => default; } class C2 : I { T?[] I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.ReturnType).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct3() { var source = @" interface I { (T a, T? b)? Goo<T>() where T : struct; } class C1 : I { public (T a, T? b)? Goo<T>() where T : struct => default; } class C2 : I { (T a, T? b)? I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); var tuple = c2Goo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter1() { var source = @" abstract class Base { public abstract void Goo<T>(T? value) where T : struct; } class Derived : Base { public override void Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter2() { var source = @" abstract class Base { public abstract void Goo<T>(T?[] value) where T : struct; } class Derived : Base { public override void Goo<T>(T?[] value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter3() { var source = @" abstract class Base { public abstract void Goo<T>((T a, T? b)? value) where T : struct; } class Derived : Base { public override void Goo<T>((T a, T? b)? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct1() { var source = @" abstract class Base { public abstract T? Goo<T>() where T : struct; } class Derived : Base { public override T? Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct2() { var source = @" abstract class Base { public abstract T?[] Goo<T>() where T : struct; } class Derived : Base { public override T?[] Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.ReturnType).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct3() { var source = @" abstract class Base { public abstract (T a, T? b)? Goo<T>() where T : struct; } class Derived : Base { public override (T a, T? b)? Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); var tuple = dGoo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter_WithStructConstraint() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T? value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (14,29): error CS8652: The feature 'constraints for override and explicit interface implementation methods' is not available in C# 7.3. Please use language version 8.0 or greater. // void I.Goo<T>(T? value) where T : struct { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "where").WithArguments("constraints for override and explicit interface implementation methods", "8.0").WithLocation(14, 29) ); } [Fact] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter_WithStructConstraint() { var source = @" abstract class Base { public abstract void Goo<T>(T? value) where T : struct; } class Derived : Base { public override void Goo<T>(T? value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); } [Fact] public void AllowStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,42): error CS8652: The feature 'constraints for override and explicit interface implementation methods' is not available in C# 7.3. Please use language version 8.0 or greater. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "where").WithArguments("constraints for override and explicit interface implementation methods", "8.0").WithLocation(9, 42) ); } [Fact] public void ErrorIfNonExistentTypeParameter_HasStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfNonExistentTypeParameter_HasClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived<U> : Base { public override void Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived<U>.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived<U>.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived<U> : Base { public override void Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived<U>.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived<U>.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void AllowStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value) where T : class; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void ErrorIfNonExistentTypeParameter_HasStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C : I { void I.Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfNonExistentTypeParameter_HasClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C : I { void I.Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C<U> : I { void I.Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C<U>.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C<U>.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C<U> : I { void I.Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C<U>.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C<U>.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfNonExistentTypeParameter() { var source = @" interface I { void Goo(); } class C : I { void I.Goo() where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0080: Constraints are not allowed on non-generic declarations // void I.Goo() where U : class { } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(9, 18) ); } [Fact] public void ErrorIfDuplicateConstraintClause() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C<U> : I { void I.Goo<T>(T? value) where T : struct where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. // void I.Goo<T>(T? value) where T : struct where T : class { } Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints1() { var source = @" abstract class Base { } class Derived : Base { public override void Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0115: 'Derived.Goo<T>(T)': no suitable method found to override // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Goo").WithArguments("Derived.Goo<T>(T)").WithLocation(8, 26), // (8,60): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 60)); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints2() { var source = @" abstract class Base { } class Derived : Base { public override void Goo<T>(T value) where T : class, struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0115: 'Derived.Goo<T>(T)': no suitable method found to override // public override void Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Goo").WithArguments("Derived.Goo<T>(T)").WithLocation(8, 26), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 59)); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints3() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,60): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(9, 60)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints1() { var source = @" interface I { } class C : I { void I.Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0539: 'C.Goo<T>(T)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C.Goo<T>(T)").WithLocation(8, 12), // (8,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 46)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints2() { var source = @" interface I { } class C : I { void I.Goo<T>(T value) where T : class, struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0539: 'C.Goo<T>(T)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C.Goo<T>(T)").WithLocation(8, 12), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 45)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints3() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(9, 46)); } [Fact] public void Error_WhenOverride_HasNullableClassConstraint() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T value) where T : class?; } class Derived : Base { public override void Goo<T>(T value) where T : class? { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class? { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 52)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasNullableClassConstraint() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class?; } class C : I { void I.Goo<T>(T value) where T : class? { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,38): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : class? { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 38)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint1() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 52)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint2() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : class, Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,59): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class, Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 59)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint3() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T, U>(T value) where T : class where U : Stream; } class Derived : Base { public override void Goo<T, U>(T value) where T : class where U : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,71): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T, U>(T value) where T : class where U Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 71)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint1() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,38): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 38)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint2() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : class, Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : class, Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 45)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint3() { var source = @" using System.IO; interface I { void Goo<T, U>(T value) where T : class where U : Stream; } class C : I { void I.Goo<T, U>(T value) where T : class where U : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,57): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T, U>(T value) where T : class where U : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 57)); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot1() { var source = @" interface I { void Goo<U>(U value); } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I.Goo<U>(U)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "U", "I.Goo<U>(U)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot2() { var source = @" interface I { void Goo<T>(T value) where T : class; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot3() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(10, 16) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot1() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot3() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot1() { var source = @" interface I { void Goo<U>(U value); } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I.Goo<U>(U)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "U", "I.Goo<U>(U)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot2() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot3() { var source = @" using System; interface I { void Goo<T>(T value) where T : Enum; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(10, 16) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot1() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot3() { var source = @" using System; abstract class Base { public abstract void Goo<T>(T value) where T : Enum; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenHasEnumConstraint() { var source = @" using System; abstract class Base { public abstract void Goo<T>(T value) where T : Enum; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenHasNullableConstraint() { var source = @" abstract class Base<U> { public abstract void Goo<T>(T value) where T : U; } class Derived : Base<int?> { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base<int?>.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base<int?>.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void NoError_WhenOverrideHasStructConstraint_AndOverriddenHasUnmanagedConstraint() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoError_WhenOverrideHasClassConstraint_AndOverriddenHasReferenceTypeConstraint() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void Error_WhenOverride_HasDefaultConstructorConstraint1() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : new(); } class Derived : Base { public override void Goo<T>(T value) where T : new() { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : new() { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "new()").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasDefaultConstructorConstraint2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class, new(); } class Derived : Base { public override void Goo<T>(T value) where T : class, new() { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,59): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class, new() { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "new()").WithLocation(9, 59) ); } [Fact] public void Error_WhenOverride_HasUnmanagedConstraint1() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged; } class Derived : Base { public override void Goo<T>(T value) where T : unmanaged { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasUnmanagedConstraint2() { var source = @" interface I {} abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged, I; } class Derived : Base { public override void Goo<T>(T value) where T : unmanaged, I { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (11,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : unmanaged, I { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(11, 52) ); } [Fact] [WorkItem(34583, "https://github.com/dotnet/roslyn/issues/34583")] public void ExplicitImplementationOfNullableStructWithMultipleTypeParameters() { var source = @" interface I { void Goo<T, U>(T? value) where T : struct; } class C1 : I { public void Goo<T, U>(T? value) where T : struct {} } class C2 : I { void I.Goo<T, U>(T? value) {} } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Areas: interface mapping, virtual/abstract/override methods, /// virtual properties, sealed members, new members, accessibility /// of inherited methods, etc. /// </summary> public class InheritanceBindingTests : CompilingTestBase { [Fact] public void TestModifiersOnExplicitImpl() { var text = @" interface IGoo { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); void Method8(); void Method9(); void Method10(); void Method11(); void Method12(); void Method13(); void Method14(); } abstract partial class AbstractGoo : IGoo { abstract void IGoo.Method1() { } virtual void IGoo.Method2() { } override void IGoo.Method3() { } sealed void IGoo.Method4() { } new void IGoo.Method5() { } public void IGoo.Method6() { } protected void IGoo.Method7() { } internal void IGoo.Method8() { } protected internal void IGoo.Method9() { } //roslyn considers 'protected internal' one modifier (two in dev10) private void IGoo.Method10() { } extern void IGoo.Method11(); //not an error (in dev10 or roslyn) static void IGoo.Method12() { } partial void IGoo.Method13(); private protected void IGoo.Method14() { } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (22,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract void IGoo.Method1() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method1").WithArguments("abstract").WithLocation(22, 24), // (23,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual void IGoo.Method2() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method2").WithArguments("virtual").WithLocation(23, 23), // (24,24): error CS0106: The modifier 'override' is not valid for this item // override void IGoo.Method3() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method3").WithArguments("override").WithLocation(24, 24), // (26,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed void IGoo.Method4() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method4").WithArguments("sealed").WithLocation(26, 22), // (28,19): error CS0106: The modifier 'new' is not valid for this item // new void IGoo.Method5() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method5").WithArguments("new").WithLocation(28, 19), // (30,22): error CS0106: The modifier 'public' is not valid for this item // public void IGoo.Method6() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method6").WithArguments("public").WithLocation(30, 22), // (31,25): error CS0106: The modifier 'protected' is not valid for this item // protected void IGoo.Method7() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method7").WithArguments("protected").WithLocation(31, 25), // (32,24): error CS0106: The modifier 'internal' is not valid for this item // internal void IGoo.Method8() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method8").WithArguments("internal").WithLocation(32, 24), // (33,34): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal void IGoo.Method9() { } //roslyn considers 'protected internal' one modifier (two in dev10) Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method9").WithArguments("protected internal").WithLocation(33, 34), // (34,23): error CS0106: The modifier 'private' is not valid for this item // private void IGoo.Method10() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method10").WithArguments("private").WithLocation(34, 23), // (37,22): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void IGoo.Method12() { } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Method12").WithArguments("static", "9.0", "preview").WithLocation(37, 22), // (40,33): error CS0106: The modifier 'private protected' is not valid for this item // private protected void IGoo.Method14() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Method14").WithArguments("private protected").WithLocation(40, 33), // (37,22): error CS0539: 'AbstractGoo.Method12()' in explicit interface declaration is not found among members of the interface that can be implemented // static void IGoo.Method12() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method12").WithArguments("AbstractGoo.Method12()").WithLocation(37, 22), // (38,23): error CS0754: A partial method may not explicitly implement an interface method // partial void IGoo.Method13(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "Method13").WithLocation(38, 23), // (20,38): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Method12()' // abstract partial class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Method12()").WithLocation(20, 38), // (36,22): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.Method11()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern void IGoo.Method11(); //not an error (in dev10 or roslyn) Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Method11").WithArguments("AbstractGoo.IGoo.Method11()").WithLocation(36, 22) ); } [Fact] public void TestModifiersOnExplicitPropertyImpl() { var text = @" interface IGoo { int Property1 { set; } int Property2 { set; } int Property3 { set; } int Property4 { set; } int Property5 { set; } int Property6 { set; } int Property7 { set; } int Property8 { set; } int Property9 { set; } int Property10 { set; } int Property11 { set; } int Property12 { set; } } abstract class AbstractGoo : IGoo { abstract int IGoo.Property1 { set { } } virtual int IGoo.Property2 { set { } } override int IGoo.Property3 { set { } } sealed int IGoo.Property4 { set { } } new int IGoo.Property5 { set { } } public int IGoo.Property6 { set { } } protected int IGoo.Property7 { set { } } internal int IGoo.Property8 { set { } } protected internal int IGoo.Property9 { set { } } //roslyn considers 'protected internal' one modifier (two in dev10) private int IGoo.Property10 { set { } } extern int IGoo.Property11 { set; } //not an error (in dev10 or roslyn) static int IGoo.Property12 { set { } } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (20,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property1").WithArguments("abstract"), // (21,22): error CS0106: The modifier 'virtual' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property2").WithArguments("virtual"), // (22,23): error CS0106: The modifier 'override' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property3").WithArguments("override"), // (24,21): error CS0106: The modifier 'sealed' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property4").WithArguments("sealed"), // (26,18): error CS0106: The modifier 'new' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property5").WithArguments("new"), // (28,21): error CS0106: The modifier 'public' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property6").WithArguments("public"), // (29,24): error CS0106: The modifier 'protected' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property7").WithArguments("protected"), // (30,23): error CS0106: The modifier 'internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property8").WithArguments("internal"), // (31,33): error CS0106: The modifier 'protected internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property9").WithArguments("protected internal"), // (32,22): error CS0106: The modifier 'private' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "Property10").WithArguments("private"), // (35,21): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int IGoo.Property12 { set { } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Property12").WithArguments("static", "9.0", "preview").WithLocation(35, 21), // (35,21): error CS0539: 'AbstractGoo.Property12' in explicit interface declaration is not found among members of the interface that can be implemented // static int IGoo.Property12 { set { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property12").WithArguments("AbstractGoo.Property12").WithLocation(35, 21), // (18,30): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Property12' // abstract class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Property12").WithLocation(18, 30), // (34,34): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.Property11.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("AbstractGoo.IGoo.Property11.set")); } [Fact] public void TestModifiersOnExplicitIndexerImpl() { var text = @" interface IGoo { int this[int x1, int x2, int x3, int x4] { set; } int this[int x1, int x2, int x3, long x4] { set; } int this[int x1, int x2, long x3, int x4] { set; } int this[int x1, int x2, long x3, long x4] { set; } int this[int x1, long x2, int x3, int x4] { set; } int this[int x1, long x2, int x3, long x4] { set; } int this[int x1, long x2, long x3, int x4] { set; } int this[int x1, long x2, long x3, long x4] { set; } int this[long x1, int x2, int x3, int x4] { set; } int this[long x1, int x2, int x3, long x4] { set; } int this[long x1, int x2, long x3, int x4] { set; } int this[long x1, int x2, long x3, long x4] { set; } } abstract class AbstractGoo : IGoo { abstract int IGoo.this[int x1, int x2, int x3, int x4] { set { } } virtual int IGoo.this[int x1, int x2, int x3, long x4] { set { } } override int IGoo.this[int x1, int x2, long x3, int x4] { set { } } sealed int IGoo.this[int x1, int x2, long x3, long x4] { set { } } new int IGoo.this[int x1, long x2, int x3, int x4] { set { } } public int IGoo.this[int x1, long x2, int x3, long x4] { set { } } protected int IGoo.this[int x1, long x2, long x3, int x4] { set { } } internal int IGoo.this[int x1, long x2, long x3, long x4] { set { } } protected internal int IGoo.this[long x1, int x2, int x3, int x4] { set { } } //roslyn considers 'protected internal' one modifier (two in dev10) private int IGoo.this[long x1, int x2, int x3, long x4] { set { } } extern int IGoo.this[long x1, int x2, long x3, int x4] { set; } //not an error (in dev10 or roslyn) static int IGoo.this[long x1, int x2, long x3, long x4] { set { } } }"; CreateCompilation(text).VerifyDiagnostics( // (20,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract"), // (21,22): error CS0106: The modifier 'virtual' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual"), // (22,23): error CS0106: The modifier 'override' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("override"), // (24,21): error CS0106: The modifier 'sealed' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("sealed"), // (26,18): error CS0106: The modifier 'new' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("new"), // (28,21): error CS0106: The modifier 'public' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("public"), // (29,24): error CS0106: The modifier 'protected' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected"), // (30,23): error CS0106: The modifier 'internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("internal"), // (31,33): error CS0106: The modifier 'protected internal' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("protected internal"), // (32,22): error CS0106: The modifier 'private' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("private"), // (35,21): error CS0106: The modifier 'static' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static"), // (34,62): warning CS0626: Method, operator, or accessor 'AbstractGoo.IGoo.this[long, int, long, int].set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("AbstractGoo.IGoo.this[long, int, long, int].set")); } [Fact, WorkItem(542158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542158")] public void TestModifiersOnExplicitEventImpl() { var text = @" interface IGoo { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; event System.Action Event7; event System.Action Event8; event System.Action Event9; event System.Action Event10; event System.Action Event11; event System.Action Event12; } abstract class AbstractGoo : IGoo { abstract event System.Action IGoo.Event1 { add { } remove { } } virtual event System.Action IGoo.Event2 { add { } remove { } } override event System.Action IGoo.Event3 { add { } remove { } } sealed event System.Action IGoo.Event4 { add { } remove { } } new event System.Action IGoo.Event5 { add { } remove { } } public event System.Action IGoo.Event6 { add { } remove { } } protected event System.Action IGoo.Event7 { add { } remove { } } internal event System.Action IGoo.Event8 { add { } remove { } } protected internal event System.Action IGoo.Event9 { add { } remove { } } //roslyn considers 'protected internal' one modifier (two in dev10) private event System.Action IGoo.Event10 { add { } remove { } } extern event System.Action IGoo.Event11 { add { } remove { } } static event System.Action IGoo.Event12 { add { } remove { } } }"; // It seems Dev11 doesn't report ERR_ExternHasBody errors for Event11 accessors // if there are other explicitly implemented members with erroneous modifiers other than extern and abstract. // If the other errors are fixed ERR_ExternHasBody is reported. // We report all errors at once since they are unrelated, not cascading. CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (20,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract event System.Action IGoo.Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event1").WithArguments("abstract"), // (21,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual event System.Action IGoo.Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event2").WithArguments("virtual"), // (22,39): error CS0106: The modifier 'override' is not valid for this item // override event System.Action IGoo.Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event3").WithArguments("override"), // (24,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed event System.Action IGoo.Event4 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event4").WithArguments("sealed"), // (26,34): error CS0106: The modifier 'new' is not valid for this item // new event System.Action IGoo.Event5 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event5").WithArguments("new"), // (28,37): error CS0106: The modifier 'public' is not valid for this item // public event System.Action IGoo.Event6 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event6").WithArguments("public"), // (29,40): error CS0106: The modifier 'protected' is not valid for this item // protected event System.Action IGoo.Event7 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event7").WithArguments("protected"), // (30,39): error CS0106: The modifier 'internal' is not valid for this item // internal event System.Action IGoo.Event8 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event8").WithArguments("internal"), // (31,49): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal event System.Action IGoo.Event9 { add { } remove { } } //roslyn considers 'protected internal' one modifier (two in dev10) Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event9").WithArguments("protected internal"), // (32,38): error CS0106: The modifier 'private' is not valid for this item // private event System.Action IGoo.Event10 { add { } remove { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Event10").WithArguments("private"), // (34,47): error CS0179: 'AbstractGoo.IGoo.Event11.add' cannot be extern and declare a body // extern event System.Action IGoo.Event11 { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("AbstractGoo.IGoo.Event11.add"), // (34,55): error CS0179: 'AbstractGoo.IGoo.Event11.remove' cannot be extern and declare a body // extern event System.Action IGoo.Event11 { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("AbstractGoo.IGoo.Event11.remove"), // (35,37): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action IGoo.Event12 { add { } remove { } } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "Event12").WithArguments("static", "9.0", "preview").WithLocation(35, 37), // (35,37): error CS0539: 'AbstractGoo.Event12' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action IGoo.Event12 { add { } remove { } } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event12").WithArguments("AbstractGoo.Event12").WithLocation(35, 37), // (18,30): error CS0535: 'AbstractGoo' does not implement interface member 'IGoo.Event12' // abstract class AbstractGoo : IGoo Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo").WithArguments("AbstractGoo", "IGoo.Event12").WithLocation(18, 30) ); } [Fact] // can't bind to events public void TestInvokeExplicitMemberDirectly() { // Tests: // Sanity check – it should be an error to invoke a member by its fully qualified explicit implementation name var text = @" interface Interface { void Method<T>(); void Method(int i, long j); long Property { set; } event System.Action Event; } class Class : Interface { void Interface.Method(int i, long j) { Interface.Method(1, 2); } void Interface.Method<T>() { Interface.Method<T>(); } long Interface.Property { set { } } event System.Action Interface.Event { add { } remove { } } void Test() { Interface.Property = 2; Interface.Event += null; Class c = new Class(); c.Interface.Method(1, 2); c.Interface.Method<string>(); c.Interface.Property = 2; c.Interface.Event += null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Method(int, long)' // Interface.Method(1, 2); Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Method").WithArguments("Interface.Method(int, long)").WithLocation(13, 9), // (18,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Method<T>()' // Interface.Method<T>(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Method<T>").WithArguments("Interface.Method<T>()").WithLocation(18, 9), // (27,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Property' // Interface.Property = 2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Property").WithArguments("Interface.Property").WithLocation(27, 9), // (28,9): error CS0120: An object reference is required for the non-static field, method, or property 'Interface.Event' // Interface.Event += null; Diagnostic(ErrorCode.ERR_ObjectRequired, "Interface.Event").WithArguments("Interface.Event").WithLocation(28, 9), // (31,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Method(1, 2); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(31, 11), // (32,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Method<string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(32, 11), // (33,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Property = 2; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(33, 11), // (34,11): error CS1061: 'Class' does not contain a definition for 'Interface' and no extension method 'Interface' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.Interface.Event += null; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Interface").WithArguments("Class", "Interface").WithLocation(34, 11)); } [Fact] public void TestHidesAbstractMethod() { var text = @" abstract class AbstractGoo { public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); } abstract class Goo : AbstractGoo { public void Method1() { } public abstract void Method2(); public virtual void Method3() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractProperty() { var text = @" abstract class AbstractGoo { public abstract long Property1 { set; } public abstract long Property2 { set; } public abstract long Property3 { set; } } abstract class Goo : AbstractGoo { public long Property1 { set { } } public abstract long Property2 { set; } public virtual long Property3 { set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractIndexer() { var text = @" abstract class AbstractGoo { public abstract long this[int x] { set; } public abstract long this[string x] { set; } public abstract long this[char x] { set; } } abstract class Goo : AbstractGoo { public long this[int x] { set { } } public abstract long this[string x] { set; } public virtual long this[char x] { set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 13, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 13, Column = 25 }, }); } [Fact] public void TestHidesAbstractEvent() { var text = @" abstract class AbstractGoo { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } abstract class Goo : AbstractGoo { public event System.Action Event1 { add { } remove { } } public abstract event System.Action Event2; public virtual event System.Action Event3 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,32): error CS0533: 'Goo.Event1' hides inherited abstract member 'AbstractGoo.Event1' // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event1").WithArguments("Goo.Event1", "AbstractGoo.Event1"), // (11,32): warning CS0114: 'Goo.Event1' hides inherited member 'AbstractGoo.Event1'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event1").WithArguments("Goo.Event1", "AbstractGoo.Event1"), // (12,41): error CS0533: 'Goo.Event2' hides inherited abstract member 'AbstractGoo.Event2' // public abstract event System.Action Event2 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event2").WithArguments("Goo.Event2", "AbstractGoo.Event2"), // (12,41): warning CS0114: 'Goo.Event2' hides inherited member 'AbstractGoo.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event2 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Goo.Event2", "AbstractGoo.Event2"), // (13,40): error CS0533: 'Goo.Event3' hides inherited abstract member 'AbstractGoo.Event3' // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event3").WithArguments("Goo.Event3", "AbstractGoo.Event3"), // (13,40): warning CS0114: 'Goo.Event3' hides inherited member 'AbstractGoo.Event3'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event3").WithArguments("Goo.Event3", "AbstractGoo.Event3")); } [Fact] public void TestNoMethodToOverride() { var text = @" interface Interface { void Method0(); } class Base { public virtual void Method1() { } private void Method2() { } } class Derived : Base, Interface { public override void Method0() { } public override void Method1(int x) { } public override void Method2() { } public override void Method3() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 16, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 18, Column = 26 }, }); } [Fact] public void TestNoPropertyToOverride() { var text = @" interface Interface { int Property0 { get; set; } } class Base { public virtual int Property1 { get; set; } private int Property2 { get; set; } public virtual int Property3 { get { return 0; } } public virtual int Property4 { get { return 0; } } public virtual int Property5 { set { } } public virtual int Property6 { set { } } public virtual int Property7 { get; set; } public virtual int Property8 { get; set; } } class Derived : Base, Interface { public override int Property0 { get; set; } //iface public override double Property1 { get; set; } //wrong type public override int Property2 { get; set; } //inaccessible public override int Property3 { set { } } //wrong accessor(s) public override int Property4 { get; set; } //wrong accessor(s) public override int Property5 { get { return 0; } } //wrong accessor(s) public override int Property6 { get; set; } //wrong accessor(s) public override int Property7 { get { return 0; } } //wrong accessor(s) public override int Property8 { set { } } //wrong accessor(s) public override int Property9 { get; set; } //nothing to override } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 21, Column = 25 }, //0 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 22, Column = 28 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 23, Column = 25 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 24, Column = 37 }, //3.set new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 25, Column = 42 }, //4.set new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 26, Column = 37 }, //5.get new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 27, Column = 37 }, //6.get new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 30, Column = 25 }, //9 }); } [Fact] public void TestNoIndexerToOverride() { var text = @" interface Interface { int this[long w, long x, long y, long z] { get; set; } } class Base { public virtual int this[long w, long x, long y, char z] { get { return 0; } set { } } private int this[long w, long x, char y, long z] { get { return 0; } set { } } public virtual int this[long w, long x, char y, char z] { get { return 0; } } public virtual int this[long w, char x, long y, long z] { get { return 0; } } public virtual int this[long w, char x, long y, char z] { set { } } public virtual int this[long w, char x, char y, long z] { set { } } public virtual int this[long w, char x, char y, char z] { get { return 0; } set { } } public virtual int this[char w, long x, long y, long z] { get { return 0; } set { } } } class Derived : Base, Interface { public override int this[long w, long x, long y, long z] { get { return 0; } set { } } //iface public override double this[long w, long x, long y, char z] { get { return 0; } set { } } //wrong type public override int this[long w, long x, char y, long z] { get { return 0; } set { } } //inaccessible public override int this[long w, long x, char y, char z] { set { } } //wrong accessor(s) public override int this[long w, char x, long y, long z] { get { return 0; } set { } } //wrong accessor(s) public override int this[long w, char x, long y, char z] { get { return 0; } } //wrong accessor(s) public override int this[long w, char x, char y, long z] { get { return 0; } set { } } //wrong accessor(s) public override int this[long w, char x, char y, char z] { get { return 0; } } //wrong accessor(s) public override int this[char w, long x, long y, long z] { set { } } //wrong accessor(s) public override int this[string s] { get { return 0; } set { } } //nothing to override } "; CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS0115: 'Derived.this[long, long, long, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long, long, long, long]"), // (22,28): error CS1715: 'Derived.this[long, long, long, char]': type must be 'int' to match overridden member 'Base.this[long, long, long, char]' Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[long, long, long, char]", "Base.this[long, long, long, char]", "int"), // (23,25): error CS0115: 'Derived.this[long, long, char, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long, long, char, long]"), // (24,64): error CS0546: 'Derived.this[long, long, char, char].set': cannot override because 'Base.this[long, long, char, char]' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[long, long, char, char].set", "Base.this[long, long, char, char]"), // (25,82): error CS0546: 'Derived.this[long, char, long, long].set': cannot override because 'Base.this[long, char, long, long]' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[long, char, long, long].set", "Base.this[long, char, long, long]"), // (26,64): error CS0545: 'Derived.this[long, char, long, char].get': cannot override because 'Base.this[long, char, long, char]' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[long, char, long, char].get", "Base.this[long, char, long, char]"), // (27,64): error CS0545: 'Derived.this[long, char, char, long].get': cannot override because 'Base.this[long, char, char, long]' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[long, char, char, long].get", "Base.this[long, char, char, long]"), // (30,25): error CS0115: 'Derived.this[string]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string]")); } [Fact] public void TestNoEventToOverride() { var text = @" interface Interface { event System.Action Event0; } class Base { public virtual event System.Action Event1 { add { } remove { } } private event System.Action Event2 { add { } remove { } } } class Derived : Base, Interface { public override event System.Action Event0 { add { } remove { } } //iface public override event System.Func<int> Event1 { add { } remove { } } //wrong type public override event System.Action Event2 { add { } remove { } } //inaccessible public override event System.Action Event3 { add { } remove { } } //nothing to override } "; CreateCompilation(text).VerifyDiagnostics( // (15,41): error CS0115: 'Derived.Event0': no suitable method found to override // public override event System.Action Event0 { add { } remove { } } //iface Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event0").WithArguments("Derived.Event0"), // (16,44): error CS1715: 'Derived.Event1': type must be 'System.Action' to match overridden member 'Base.Event1' // public override event System.Func<int> Event1 { add { } remove { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Event1").WithArguments("Derived.Event1", "Base.Event1", "System.Action"), // (17,41): error CS0115: 'Derived.Event2': no suitable method found to override // public override event System.Action Event2 { add { } remove { } } //inaccessible Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event2").WithArguments("Derived.Event2"), // (18,41): error CS0115: 'Derived.Event3': no suitable method found to override // public override event System.Action Event3 { add { } remove { } } //nothing to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Event3").WithArguments("Derived.Event3")); } [Fact] public void TestSuppressOverrideNotExpectedErrorWhenMethodParameterTypeNotFound() { var text = @" class Base { } class Derived : Base { public override void Method0(String x) { } public override void Method1(string x, String y) { } public override void Method2(String[] x) { } public override void Method3(System.Func<String> x) { } public override void Method4((string a, String b) x) { } public override void Method5(System.Func<(string a, String[] b)> x) { } public override void Method6(Outer<String>.Inner<string> x) { } public override void Method7(Outer<string>.Inner<String> x) { } public override void Method8(Int? x) { } } class Outer<T> { public class Inner<U>{} } "; CreateCompilation(text).VerifyDiagnostics( // (8,34): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method0(String x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(8, 34), // (9,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method1(string x, String y) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 44), // (10,34): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method2(String[] x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 34), // (11,46): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method3(System.Func<String> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 46), // (12,45): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method4((string a, String b) x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 45), // (13,57): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method5(System.Func<(string a, String[] b)> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 57), // (14,40): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method6(Outer<String>.Inner<string> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 40), // (15,54): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override void Method7(Outer<string>.Inner<String> x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 54), // (16,34): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override void Method8(Int? x) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 34)); } [Fact] public void TestSuppressOverrideNotExpectedErrorWhenIndexerParameterTypeNotFound() { var text = @" class Base { } class Derived : Base { public override int this[String x] => 0; public override int this[string x, String y] => 0; public override int this[String[] x] => 0; public override int this[System.Func<String> x] => 0; public override int this[(string a, String b) x] => 0; public override int this[System.Func<(string a, String[] b)> x] => 0; public override int this[Outer<String>.Inner<string> x] => 0; public override int this[Outer<string>.Inner<String> x] => 0; public override int this[Int? x] => 0; } class Outer<T> { public class Inner<U>{} } "; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[String x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(8, 30), // (9,40): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[string x, String y] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 40), // (10,30): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[String[] x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 30), // (11,42): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[System.Func<String> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 42), // (12,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[(string a, String b) x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 41), // (13,53): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[System.Func<(string a, String[] b)> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 53), // (14,36): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Outer<String>.Inner<string> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 36), // (15,50): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Outer<string>.Inner<String> x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 50), // (16,30): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override int this[Int? x] => 0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 30)); } [Fact] public void TestSuppressCantChangeReturnTypeErrorWhenMethodReturnTypeNotFound() { var text = @" abstract class Base { public abstract void Method0(); public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); public abstract void Method4(); public abstract void Method5(); public abstract void Method6(); public abstract void Method7(); } class Derived : Base { public override String Method0() => null; public override String[] Method1() => null; public override System.Func<String> Method2() => null; public override (string a, String b) Method3() => (null, null); public override System.Func<(string a, String[] b)> Method4() => null; public override Outer<String>.Inner<string> Method5() => null; public override Outer<string>.Inner<String> Method6() => null; public override Int? Method7() => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String Method0() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 21), // (17,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] Method1() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 21), // (18,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> Method2() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 33), // (19,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) Method3() => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 32), // (20,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> Method4() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 44), // (21,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> Method5() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 27), // (22,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> Method6() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 41), // (23,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? Method7() => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 21)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenPropertyTypeNotFound() { var text = @" abstract class Base { public abstract int Property0 { get; } public abstract int Property1 { get; } public abstract int Property2 { get; } public abstract int Property3 { get; } public abstract int Property4 { get; } public abstract int Property5 { get; } public abstract int Property6 { get; } public abstract int Property7 { get; } } class Derived : Base { public override String Property0 => null; public override String[] Property1 => null; public override System.Func<String> Property2 => null; public override (string a, String b) Property3 => (null, null); public override System.Func<(string a, String[] b)> Property4 => null; public override Outer<String>.Inner<string> Property5 => null; public override Outer<string>.Inner<String> Property6 => null; public override Int? Property7 => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String Property0 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 21), // (17,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] Property1 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 21), // (18,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> Property2 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 33), // (19,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) Property3 => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 32), // (20,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> Property4 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 44), // (21,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> Property5 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 27), // (22,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> Property6 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 41), // (23,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? Property7 => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 21)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenIndexerTypeNotFound() { var text = @" abstract class Base { public abstract int this[int index] { get; } } class Derived : Base { public override String this[int index] => null; public override String[] this[int index] => null; public override System.Func<String> this[int index] => null; public override (string a, String b) this[int index] => (null, null); public override System.Func<(string a, String[] b)> this[int index] => null; public override Outer<String>.Inner<string> this[int index] => null; public override Outer<string>.Inner<String> this[int index] => null; public override Int? this[int index] => null; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(9, 21), // (10,21): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override String[] this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(10, 21), // (11,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<String> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(11, 33), // (12,32): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override (string a, String b) this[int index] => (null, null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(12, 32), // (13,44): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override System.Func<(string a, String[] b)> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(13, 44), // (14,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<String>.Inner<string> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(14, 27), // (15,41): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override Outer<string>.Inner<String> this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(15, 41), // (16,21): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override Int? this[int index] => null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(16, 21), // (10,30): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override String[] this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(10, 30), // (11,41): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override System.Func<String> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(11, 41), // (12,42): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override (string a, String b) this[int index] => (null, null); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(12, 42), // (13,57): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override System.Func<(string a, String[] b)> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(13, 57), // (14,49): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Outer<String>.Inner<string> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(14, 49), // (15,49): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Outer<string>.Inner<String> this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(15, 49), // (16,26): error CS0111: Type 'Derived' already defines a member called 'this' with the same parameter types // public override Int? this[int index] => null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "Derived").WithLocation(16, 26)); } [Fact] public void TestSuppressCantChangeTypeErrorWhenEventTypeNotFound() { var text = @" abstract class Base { public abstract event System.Action Event0; public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; public abstract event System.Action Event4; public abstract event System.Action Event5; public abstract event System.Action Event6; public abstract event System.Action Event7; } class Derived : Base { public override event String Event0; public override event String[] Event1; public override event System.Func<String> Event2; public override event (string a, String b) Event3; public override event System.Func<(string a, String[] b)> Event4; public override event Outer<String>.Inner<string> Event5; public override event Outer<string>.Inner<String> Event6; public override event Int? Event7; } class Outer<T> { public class Inner<U> { } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event String Event0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(16, 27), // (17,27): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event String[] Event1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(17, 27), // (18,39): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event System.Func<String> Event2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(18, 39), // (19,38): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event (string a, String b) Event3; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(19, 38), // (20,50): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event System.Func<(string a, String[] b)> Event4; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(20, 50), // (21,33): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(21, 33), // (22,47): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "String").WithArguments("String").WithLocation(22, 47), // (23,27): error CS0246: The type or namespace name 'Int' could not be found (are you missing a using directive or an assembly reference?) // public override event Int? Event7; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Int").WithArguments("Int").WithLocation(23, 27), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event6.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event6.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event5.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event5.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event4.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event4.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event4.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event4.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event7.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event7.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event0.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event0.add").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event6.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event6.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event7.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event7.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event0.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event0.remove").WithLocation(14, 7), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event5.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event5.remove").WithLocation(14, 7), // (17,36): error CS0066: 'Derived.Event1': event must be of a delegate type // public override event String[] Event1; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event1").WithArguments("Derived.Event1").WithLocation(17, 36), // (19,48): error CS0066: 'Derived.Event3': event must be of a delegate type // public override event (string a, String b) Event3; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event3").WithArguments("Derived.Event3").WithLocation(19, 48), // (21,55): error CS0066: 'Derived.Event5': event must be of a delegate type // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event5").WithArguments("Derived.Event5").WithLocation(21, 55), // (22,55): error CS0066: 'Derived.Event6': event must be of a delegate type // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event6").WithArguments("Derived.Event6").WithLocation(22, 55), // (23,32): error CS0066: 'Derived.Event7': event must be of a delegate type // public override event Int? Event7; Diagnostic(ErrorCode.ERR_EventNotDelegate, "Event7").WithArguments("Derived.Event7").WithLocation(23, 32), // (19,48): warning CS0067: The event 'Derived.Event3' is never used // public override event (string a, String b) Event3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event3").WithArguments("Derived.Event3").WithLocation(19, 48), // (23,32): warning CS0067: The event 'Derived.Event7' is never used // public override event Int? Event7; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event7").WithArguments("Derived.Event7").WithLocation(23, 32), // (17,36): warning CS0067: The event 'Derived.Event1' is never used // public override event String[] Event1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event1").WithArguments("Derived.Event1").WithLocation(17, 36), // (22,55): warning CS0067: The event 'Derived.Event6' is never used // public override event Outer<string>.Inner<String> Event6; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event6").WithArguments("Derived.Event6").WithLocation(22, 55), // (18,47): warning CS0067: The event 'Derived.Event2' is never used // public override event System.Func<String> Event2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event2").WithArguments("Derived.Event2").WithLocation(18, 47), // (21,55): warning CS0067: The event 'Derived.Event5' is never used // public override event Outer<String>.Inner<string> Event5; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event5").WithArguments("Derived.Event5").WithLocation(21, 55), // (20,63): warning CS0067: The event 'Derived.Event4' is never used // public override event System.Func<(string a, String[] b)> Event4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event4").WithArguments("Derived.Event4").WithLocation(20, 63), // (16,34): warning CS0067: The event 'Derived.Event0' is never used // public override event String Event0; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event0").WithArguments("Derived.Event0").WithLocation(16, 34)); } [Fact] public void TestOverrideSealedMethod() { var text = @" class Base { public sealed override string ToString() { return ""Base""; } } class Derived : Base { public override string ToString() { return ""Derived""; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 12, Column = 28 }, }); } [Fact] public void TestOverrideSealedProperty() { var text = @" class Base0 { public virtual int Property { get; set; } } class Base : Base0 { public sealed override int Property { get; set; } } class Derived : Base { public override int Property { get; set; } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived.Property }); } [Fact] public void TestOverrideSealedIndexer() { var text = @" class Base0 { public virtual int this[int x] { get { return 0; } set { } } } class Base : Base0 { public sealed override int this[int x] { get { return 0; } set { } } } class Derived : Base { public override int this[int x] { get { return 0; } set { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the indexer itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived indexer }); } [Fact] public void TestOverrideSealedEvents() { var text = @" class Base0 { public virtual event System.Action Event { add { } remove { } } } class Base : Base0 { public sealed override event System.Action Event { add { } remove { } } } class Derived : Base { public override event System.Action Event { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,41): error CS0239: 'Derived.Event': cannot override inherited member 'Base.Event' because it is sealed // public override event System.Action Event { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Event").WithArguments("Derived.Event", "Base.Event")); } [Fact] public void TestOverrideSealedPropertyOmitAccessors() { var text = @" class Base0 { public virtual int Property { get; set; } } class Base : Base0 { public sealed override int Property { set { } } } class Derived : Base { public override int Property { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived.Property }); } [Fact] public void TestOverrideSealedIndexerOmitAccessors() { var text = @" class Base0 { public virtual int this[int x] { get { return 0; } set { } } } class Base : Base0 { public sealed override int this[int x] { set { } } } class Derived : Base { public override int this[int x] { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 14, Column = 25 }, //Derived indexer }); } [Fact] public void TestOverrideSameMemberMultipleTimes() { // Tests: // Override same virtual / abstract member more than once in different parts of a (partial) derived type var text = @" using str = System.String; class Base { public virtual string Method1() { return string.Empty; } public virtual string Method2() { return string.Empty; } } class Derived : Base { public override System.String Method1() { return null; } public override string Method1() { return null; } } partial class Derived2 : Base { public override string Method2() { return null; } } partial class Derived2 { public override string Method2() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,28): error CS0111: Type 'Derived' already defines a member called 'Method1' with the same parameter types // public override string Method1() { return null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method1").WithArguments("Method1", "Derived"), // (22,28): error CS0111: Type 'Derived2' already defines a member called 'Method2' with the same parameter types // public override string Method2() { return null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method2").WithArguments("Method2", "Derived2"), // (2,1): info CS8019: Unnecessary using directive. // using str = System.String; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using str = System.String;")); } [Fact] public void TestOverrideNonMethodWithMethod() { var text = @" class Base { public int field; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; } class Derived : Base { public override int field() { return 1; } public override int Property() { return 1; } public override int Interface() { return 1; } public override int Class() { return 1; } public override int Struct() { return 1; } public override int Enum() { return 1; } public override int Delegate() { return 1; } public override int Event() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,25): error CS0505: 'Derived.field()': cannot override because 'Base.field' is not a function // public override int field() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "field").WithArguments("Derived.field()", "Base.field"), // (17,25): error CS0505: 'Derived.Property()': cannot override because 'Base.Property' is not a function // public override int Property() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Property").WithArguments("Derived.Property()", "Base.Property"), // (18,25): error CS0505: 'Derived.Interface()': cannot override because 'Base.Interface' is not a function // public override int Interface() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Interface").WithArguments("Derived.Interface()", "Base.Interface"), // (19,25): error CS0505: 'Derived.Class()': cannot override because 'Base.Class' is not a function // public override int Class() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Class").WithArguments("Derived.Class()", "Base.Class"), // (20,25): error CS0505: 'Derived.Struct()': cannot override because 'Base.Struct' is not a function // public override int Struct() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Struct").WithArguments("Derived.Struct()", "Base.Struct"), // (21,25): error CS0505: 'Derived.Enum()': cannot override because 'Base.Enum' is not a function // public override int Enum() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Enum").WithArguments("Derived.Enum()", "Base.Enum"), // (22,25): error CS0505: 'Derived.Delegate()': cannot override because 'Base.Delegate' is not a function // public override int Delegate() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Delegate").WithArguments("Derived.Delegate()", "Base.Delegate"), // (23,25): error CS0505: 'Derived.Event()': cannot override because 'Base.Event' is not a function // public override int Event() { return 1; } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Event").WithArguments("Derived.Event()", "Base.Event"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0"), // (11,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event") ); } [Fact] public void TestOverrideNonPropertyWithProperty() { var text = @" class Base { public int field; public int Method() { return 0; } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; } class Derived : Base { public override int field { get; set; } public override int Method { get; set; } public override int Interface { get; set; } public override int Class { get; set; } public override int Struct { get; set; } public override int Enum { get; set; } public override int Delegate { get; set; } public override int Event { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,25): error CS0544: 'Derived.field': cannot override because 'Base.field' is not a property // public override int field { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "field").WithArguments("Derived.field", "Base.field"), // (17,25): error CS0544: 'Derived.Method': cannot override because 'Base.Method()' is not a property // public override int Method { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Method").WithArguments("Derived.Method", "Base.Method()"), // (18,25): error CS0544: 'Derived.Interface': cannot override because 'Base.Interface' is not a property // public override int Interface { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (19,25): error CS0544: 'Derived.Class': cannot override because 'Base.Class' is not a property // public override int Class { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Class").WithArguments("Derived.Class", "Base.Class"), // (20,25): error CS0544: 'Derived.Struct': cannot override because 'Base.Struct' is not a property // public override int Struct { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (21,25): error CS0544: 'Derived.Enum': cannot override because 'Base.Enum' is not a property // public override int Enum { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (22,25): error CS0544: 'Derived.Delegate': cannot override because 'Base.Delegate' is not a property // public override int Delegate { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (23,25): error CS0544: 'Derived.Event': cannot override because 'Base.Event' is not a property // public override int Event { get; set; } Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Event").WithArguments("Derived.Event", "Base.Event"), // (11,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0") ); } [Fact] public void TestOverrideNonEventWithEvent() { var text = @" class Base { public int field; public int Property { get { return 0; } } public int Method() { return 0; } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); } class Derived : Base { public override event System.Action field { add { } remove { } } public override event System.Action Property { add { } remove { } } public override event System.Action Method { add { } remove { } } public override event System.Action Interface { add { } remove { } } public override event System.Action Class { add { } remove { } } public override event System.Action Struct { add { } remove { } } public override event System.Action Enum { add { } remove { } } public override event System.Action Delegate { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (16,41): error CS0072: 'Derived.field': cannot override; 'Base.field' is not an event // public override event System.Action field { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "field").WithArguments("Derived.field", "Base.field"), // (17,41): error CS0072: 'Derived.Property': cannot override; 'Base.Property' is not an event // public override event System.Action Property { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Property").WithArguments("Derived.Property", "Base.Property"), // (18,41): error CS0072: 'Derived.Method': cannot override; 'Base.Method()' is not an event // public override event System.Action Method { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Method").WithArguments("Derived.Method", "Base.Method()"), // (19,41): error CS0072: 'Derived.Interface': cannot override; 'Base.Interface' is not an event // public override event System.Action Interface { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (20,41): error CS0072: 'Derived.Class': cannot override; 'Base.Class' is not an event // public override event System.Action Class { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Class").WithArguments("Derived.Class", "Base.Class"), // (21,41): error CS0072: 'Derived.Struct': cannot override; 'Base.Struct' is not an event // public override event System.Action Struct { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (22,41): error CS0072: 'Derived.Enum': cannot override; 'Base.Enum' is not an event // public override event System.Action Enum { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (23,41): error CS0072: 'Derived.Delegate': cannot override; 'Base.Delegate' is not an event // public override event System.Action Delegate { add { } remove { } } Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (4,16): warning CS0649: Field 'Base.field' is never assigned to, and will always have its default value 0 // public int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("Base.field", "0") ); } [Fact] public void TestOverrideNonVirtualMethod() { var text = @" class Base { public virtual void Method1() { } } class Derived : Base { public new void Method1() { } public void Method2() { } } class Derived2 : Derived { public override void Method1() { } public override void Method2() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualProperty() { var text = @" class Base { public virtual long Property1 { get; set; } } class Derived : Base { public new long Property1 { get; set; } public long Property2 { get; set; } } class Derived2 : Derived { public override long Property1 { get; set; } public override long Property2 { get; set; } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualIndexer() { var text = @" class Base { public virtual long this[int x] { get { return 0; } set { } } } class Derived : Base { public new long this[int x] { get { return 0; } set { } } public long this[string x] { get { return 0; } set { } } } class Derived2 : Derived { public override long this[int x] { get { return 0; } set { } } public override long this[string x] { get { return 0; } set { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the indexer itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualPropertyOmitAccessors() { var text = @" class Base { public virtual long Property1 { get; set; } } class Derived : Base { public new long Property1 { get { return 0; } } public long Property2 { get; set; } } class Derived2 : Derived { public override long Property1 { set { } } public override long Property2 { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualIndexerOmitAccessors() { var text = @" class Base { public virtual long this[int x] { get { return 0; } set { } } } class Derived : Base { public new long this[int x] { get { return 0; } } public long this[string x] { get { return 0; } set { } } } class Derived2 : Derived { public override long this[int x] { set { } } public override long this[string x] { get { return 0; } } } "; // CONSIDER: Dev10 reports on accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 26 }, }); } [Fact] public void TestOverrideNonVirtualEvent() { var text = @" class Base { public virtual event System.Action Event1 { add { } remove { } } } class Derived : Base { public new event System.Action Event1 { add { } remove { } } public event System.Action Event2 { add { } remove { } } } class Derived2 : Derived { public override event System.Action Event1 { add { } remove { } } public override event System.Action Event2 { add { } remove { } } } "; // CONSIDER: Dev10 reports on both accessors, but not on the property itself CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 15, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 16, Column = 41 }, }); } [Fact] public void TestChangeMethodReturnType() { var text = @" using str = System.String; class Base { public virtual string Method1() { return string.Empty; } public virtual string Method2() { return string.Empty; } public virtual string Method3() { return string.Empty; } public virtual string Method4() { return string.Empty; } public virtual string Method5() { return string.Empty; } } class Derived : Base { public override System.String Method1() { return null; } public override str Method2() { return null; } public override object Method3() { return null; } public override int Method4() { return 0; } public override void Method5() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 17, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 18, Column = 25 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 19, Column = 26 }, //5 }); } [Fact] public void TestChangeMethodRefReturn() { var text = @" class Base { public virtual int Method1() { return 0; } public virtual ref int Method2(ref int i) { return ref i; } public virtual ref int Method3(ref int i) { return ref i; } } class Derived : Base { int field = 0; public override ref int Method1() { return ref field; } public override int Method2(ref int i) { return i; } public override ref int Method3(ref int i) { return ref i; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,29): error CS8148: 'Derived.Method1()' must match by reference return of overridden member 'Base.Method1()' // public override ref int Method1() { return ref field; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method1").WithArguments("Derived.Method1()", "Base.Method1()").WithLocation(13, 29), // (14,25): error CS8148: 'Derived.Method2(ref int)' must match by reference return of overridden member 'Base.Method2(ref int)' // public override int Method2(ref int i) { return i; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method2").WithArguments("Derived.Method2(ref int)", "Base.Method2(ref int)").WithLocation(14, 25)); } [Fact] public void TestChangeMethodParameters() { // Tests: // Change parameter count / types of overridden member // Omit / toggle ref / out in overridden member // Override base member with a signature that only differs by optional parameters // Override base member with a signature that only differs by params // Change default value of optional argument in overridden member var text = @" using str = System.String; using integer = System.Int32; abstract class Base { public virtual string Method1(int i) { return string.Empty; } public virtual string Method2(long j) { return string.Empty; } public virtual string Method2(short j) { return string.Empty; } public virtual string Method3(System.Exception x, System.ArgumentException y) { return string.Empty; } public virtual string Method3(System.ArgumentException x, System.Exception y) { return string.Empty; } public abstract string Method4(str[] x, str[][] y); public abstract string Method5(System.Collections.Generic.List<str> x, System.Collections.Generic.Dictionary<int, long> y); public virtual string Method6(int i, params long[] j) { return string.Empty; } public virtual string Method7(int i, short j = 1) { return string.Empty; } public virtual string Method8(ref long j) { return string.Empty; } public abstract string Method9(out int j); } abstract class Derived : Base { public override str Method1(int i, long j = 1) { return string.Empty; } public override str Method1(int i, params int[] j) { return string.Empty; } public override str Method1(double i) { return string.Empty; } public override str Method2(int j) { return string.Empty; } public override str Method3(System.Exception x, System.ArgumentException y, System.Exception z) { return string.Empty; } public override str Method3(System.ArgumentException x, System.ArgumentException y) { return string.Empty; } public override str Method3() { return string.Empty; } public override str Method3(System.Exception x) { return string.Empty; } public override str Method4(str[] x, str[] y) { return string.Empty; } public override str Method4(str[][] y, str[] x) { return string.Empty; } public override str Method4(str[] x) { return string.Empty; } public override str Method5(System.Collections.Generic.List<int> x, System.Collections.Generic.Dictionary<str, long> y) { return string.Empty; } public override str Method5(System.Collections.Generic.Dictionary<int, long> x, System.Collections.Generic.List<string> y) { return string.Empty; } public override str Method5(System.Collections.Generic.List<string> y, System.Collections.Generic.Dictionary<integer, long> x) { return string.Empty; } // Not an error public override str Method6(int i, long j = 1) { return string.Empty; } public override str Method6(int i) { return string.Empty; } public override str Method7(int i, params short[] j) { return string.Empty; } public override str Method7(int i) { return string.Empty; } public override str Method7(int i, short j = 1, short k = 1) { return string.Empty; } public override str Method8(out long j) { j = 1; return string.Empty; } public override str Method8(long j) { return string.Empty; } public override str Method9(ref int j) { return string.Empty; } public override str Method9(int j) { return string.Empty; } public override str Method1(ref int i) { return string.Empty; } public override str Method2(out long j) { j = 2; return string.Empty; } public override str Method7(int i, short j = short.MaxValue) { return string.Empty; } // Not an error } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 20, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 21, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 22, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 23, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 24, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 25, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 26, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 27, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 28, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 29, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 30, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 31, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 32, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 34, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 35, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 36, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 37, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 38, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 39, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 41, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 42, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 43, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 44, Column = 25 } }); } [Fact] public void TestChangePropertyType() { var text = @" using str = System.String; class Base { public virtual string Property1 { get; set; } public virtual string Property2 { get; set; } public virtual string Property3 { get; set; } public virtual string Property4 { get; set; } } class Derived : Base { public override System.String Property1 { get; set; } public override str Property2 { get; set; } public override object Property3 { get; set; } public override int Property4 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 25 }, //4 }); } [Fact] public void TestChangePropertyRefReturn() { var text = @" class Base { int field = 0; public virtual int Proprty1 { get { return 0; } } public virtual ref int Property2 { get { return ref field; } } public virtual ref int Property3 { get { return ref field; } } } class Derived : Base { int field = 0; public override ref int Proprty1 { get { return ref field; } } public override int Property2 { get { return 0; } } public override ref int Property3 { get { return ref field; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,29): error CS8148: 'Derived.Proprty1' must match by reference return of overridden member 'Base.Proprty1' // public override ref int Proprty1 { get { return ref field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Proprty1").WithArguments("Derived.Proprty1", "Base.Proprty1").WithLocation(15, 29), // (16,25): error CS8148: 'Derived.Property2' must match by reference return of overridden member 'Base.Property2' // public override int Property2 { get { return 0; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property2").WithArguments("Derived.Property2", "Base.Property2").WithLocation(16, 25)); } [Fact] public void TestChangeIndexerType() { var text = @" using str = System.String; class Base { public virtual string this[int x, int y] { get { return null; } set { } } public virtual string this[int x, string y] { get { return null; } set { } } public virtual string this[string x, int y] { get { return null; } set { } } public virtual string this[string x, string y] { get { return null; } set { } } } class Derived : Base { public override System.String this[int x, int y] { get { return null; } set { } } public override str this[int x, string y] { get { return null; } set { } } public override object this[string x, int y] { get { return null; } set { } } public override int this[string x, string y] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 28 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 25 }, //4 }); } [Fact] public void TestChangeIndexerRefReturn() { var text = @" class Base { int field = 0; public virtual int this[int x, int y] { get { return field; } } public virtual ref int this[int x, string y] { get { return ref field; } } public virtual ref int this[string x, int y] { get { return ref field; } } } class Derived : Base { int field = 0; public override ref int this[int x, int y] { get { return ref field; } } public override int this[int x, string y] { get { return field; } } public override ref int this[string x, int y] { get { return ref field; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,29): error CS8148: 'Derived.this[int, int]' must match by reference return of overridden member 'Base.this[int, int]' // public override ref int this[int x, int y] { get { return ref field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[int, int]", "Base.this[int, int]").WithLocation(15, 29), // (16,25): error CS8148: 'Derived.this[int, string]' must match by reference return of overridden member 'Base.this[int, string]' // public override int this[int x, string y] { get { return field; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[int, string]", "Base.this[int, string]").WithLocation(16, 25)); } /// <summary> /// Based on Method1 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters1() { var text = @" abstract class Base { public virtual string this[int i] { set { } } } abstract class Derived : Base { public override string this[int i, long j = 1] { set { } } public override string this[int i, params int[] j] { set { } } public override string this[double i] { set { } } public override string this[ref int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,28): error CS0115: 'Derived.this[int, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, long]"), // (9,28): error CS0115: 'Derived.this[int, params int[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, params int[]]"), // (10,28): error CS0115: 'Derived.this[double]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[double]"), // (11,28): error CS0115: 'Derived.this[ref int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[ref int]")); } /// <summary> /// Based on Method2 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters2() { var text = @" abstract class Base { public virtual string this[long j] { set { } } public virtual string this[short j] { set { } } } abstract class Derived : Base { public override string this[int j] { set { } } public override string this[out long j] { set { j = 2; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]"), // (10,28): error CS0115: 'Derived.this[out long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[out long]")); } /// <summary> /// Based on Method3 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters3() { var text = @" abstract class Base { public virtual string this[System.Exception x, System.ArgumentException y] { set { } } public virtual string this[System.ArgumentException x, System.Exception y] { set { } } } abstract class Derived : Base { public override string this[System.Exception x, System.ArgumentException y, System.Exception z] { set { } } public override string this[System.ArgumentException x, System.ArgumentException y] { set { } } public override string this[] { set { } } public override string this[System.Exception x] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,33): error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "]"), // (9,28): error CS0115: 'Derived.this[System.Exception, System.ArgumentException, System.Exception]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Exception, System.ArgumentException, System.Exception]"), // (10,28): error CS0115: 'Derived.this[System.ArgumentException, System.ArgumentException]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.ArgumentException, System.ArgumentException]"), // (11,28): error CS0115: 'Derived.this': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this"), // (12,28): error CS0115: 'Derived.this[System.Exception]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Exception]")); } /// <summary> /// Based on Method4 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters4() { var text = @" abstract class Base { public abstract string this[string[] x, string[][] y] { set; } } abstract class Derived : Base { public override string this[string[] x, string[] y] { set { } } public override string this[string[][] y, string[] x] { set { } } public override string this[string[] x] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[string[], string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[], string[]]"), // (9,28): error CS0115: 'Derived.this[string[][], string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[][], string[]]"), // (10,28): error CS0115: 'Derived.this[string[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[string[]]")); } /// <summary> /// Based on Method5 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters5() { var text = @" abstract class Base { public abstract string this[System.Collections.Generic.List<string> x, System.Collections.Generic.Dictionary<int, long> y] { set; } } abstract class Derived : Base { public override string this[System.Collections.Generic.List<int> x, System.Collections.Generic.Dictionary<string, long> y] { set { } } public override string this[System.Collections.Generic.Dictionary<int, long> x, System.Collections.Generic.List<string> y] { set { } } public override string this[System.Collections.Generic.List<string> y, System.Collections.Generic.Dictionary<int, long> x] { set { } } // Not an error } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<string, long>]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<string, long>]"), // (9,28): error CS0115: 'Derived.this[System.Collections.Generic.Dictionary<int, long>, System.Collections.Generic.List<string>]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[System.Collections.Generic.Dictionary<int, long>, System.Collections.Generic.List<string>]")); } /// <summary> /// Based on Method6 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters6() { var text = @" abstract class Base { public virtual string this[int i, params long[] j] { set { } } } abstract class Derived : Base { public override string this[int i, long j = 1] { set { } } public override string this[int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[int, long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, long]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]")); } /// <summary> /// Based on Method7 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters7() { var text = @" abstract class Base { public virtual string this[int i, short j = 1] { set { } } } abstract class Derived : Base { public override string this[int i, params short[] j] { set { } } public override string this[int i] { set { } } public override string this[int i, short j = 1, short k = 1] { set { } } public override string this[int i, short j = short.MaxValue] { set { } } // Not an error } "; CreateCompilation(text).VerifyDiagnostics( // (8,28): error CS0115: 'Derived.this[int, params short[]]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, params short[]]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]"), // (10,28): error CS0115: 'Derived.this[int, short, short]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int, short, short]")); } /// <summary> /// Based on Method8 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters8() { var text = @" abstract class Base { public virtual string this[ref long j] { set { } } } abstract class Derived : Base { public override string this[out long j] { set { j = 1; } } public override string this[long j] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,32): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (8,28): error CS0115: 'Derived.this[out long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[out long]"), // (9,28): error CS0115: 'Derived.this[long]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[long]")); } /// <summary> /// Based on Method9 in TestChangeMethodParameters. /// </summary> [Fact] public void TestChangeIndexerParameters9() { var text = @" abstract class Base { public abstract string this[out int j] { set; } } abstract class Derived : Base { public override string this[ref int j] { set { } } public override string this[int j] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out"), // (8,33): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref"), // (8,28): error CS0115: 'Derived.this[ref int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[ref int]"), // (9,28): error CS0115: 'Derived.this[int]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[int]")); } [Fact] public void TestChangeEventType() { var text = @" using str = System.String; class Base { public virtual event System.Action<string> Event1 { add { } remove { } } public virtual event System.Action<string> Event2 { add { } remove { } } public virtual event System.Action<string> Event3 { add { } remove { } } public virtual event System.Action<string> Event4 { add { } remove { } } } class Derived : Base { public override event System.Action<System.String> Event1 { add { } remove { } } public override event System.Action<str> Event2 { add { } remove { } } public override event System.Action<object> Event3 { add { } remove { } } public override event System.Action<int> Event4 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 16, Column = 49 }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 17, Column = 46 }, //4 }); } [Fact] public void TestChangeGenericMethodReturnType() { var text = @" class Base<T> { public virtual T Method1(T t) { return t; } public virtual U Method2<U>(U u) { return u; } } class Derived : Base<string> { public override object Method1(string t) { return null; } public override object Method2<U>(U u) { return null; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 10, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 11, Column = 28 }, }); } [Fact] public void TestChangeGenericMethodParameters() { // Tests: // Change number / order / types of method parameters in overridden method var text = @" using System.Collections.Generic; abstract class Base<T, U> { protected virtual void Method(T x) { } protected virtual void Method(List<T> x) { } protected virtual void Method<V>(V x, T y) { } protected virtual void Method<V>(List<V> x, List<U> y) { } } class Derived<A, B> : Base<A, B> { protected override void Method(B x) { } protected override void Method(List<B> x) { } protected override void Method<V>(A x, V y) { } protected override void Method<V>(List<V> x, List<A> y) { } protected override void Method<V, U>(List<V> x, List<U> y) { } } class Derived : Base<long, int> { protected override void Method(int x) { } protected override void Method(List<int> x) { } protected override void Method<V>(int x, long y) { } protected override void Method<V>(List<V> x, List<long> y) { } protected override void Method<V>(List<long> x, List<int> y) { } } class Derived<A, B, C> : Base<A, B> { protected override void Method() { } protected override void Method(List<A> x, List<B> y) { } protected override void Method<V>(V x, A y, C z) { } protected override void Method<V>(List<V> x, ref List<B> y) { } protected override void Method<V>(List<V> x, List<B> y = null) { } // Not an error protected override void Method<V>(List<V> x, List<B>[] y) { } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method(B)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method(System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V>(A, V)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<A>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B>.Method<V, U>(System.Collections.Generic.List<V>, System.Collections.Generic.List<U>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(System.Collections.Generic.List<int>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, long)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<long>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(System.Collections.Generic.List<long>, System.Collections.Generic.List<int>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method(System.Collections.Generic.List<A>, System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(V, A, C)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(System.Collections.Generic.List<V>, ref System.Collections.Generic.List<B>)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived<A, B, C>.Method<V>(System.Collections.Generic.List<V>, System.Collections.Generic.List<B>[])")); } [Fact] public void TestChangeGenericMethodTypeParameters() { // Tests: // Change number / order of generic method type parameters in overridden method var text = @" using System.Collections.Generic; class Base<T, U> { protected virtual void Method<V>() { } protected virtual void Method<V>(V x, T y) { } protected virtual void Method<V, W>(T x, U y) { } protected virtual void Method<V, W>(List<V> x, List<W> y) { } } class Derived : Base<int, int> { protected override void Method() { } protected override void Method<V, U>() { } protected override void Method<V>(int x, V y) { } protected override void Method<V, U>(V x, int y) { } protected override void Method(int x, int y) { } protected override void Method<V>(int x, int y) { } protected override void Method<V, U, W>(int x, int y) { } protected override void Method<V, W>(List<W> x, List<V> y) { } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U>()"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, V)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U>(V, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V>(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, U, W>(int, int)"), Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Derived.Method<V, W>(System.Collections.Generic.List<W>, System.Collections.Generic.List<V>)")); } [Fact] public void TestChangeGenericPropertyType() { var text = @" class Base<T> { public virtual T Property1 { get; set; } public virtual T Property2 { get; set; } } class Derived : Base<string> { public override string Property1 { get; set; } public override object Property2 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 11, Column = 28 }, //2 }); } [Fact] public void TestChangeGenericIndexerType() { var text = @" class Base<T> { public virtual T this[int x] { get { return default(T); } set { } } public virtual T this[string x] { get { return default(T); } set { } } } class Derived : Base<string> { public override string this[int x] { get { return null; } set { } } public override object this[string x] { get { return null; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS1715: 'Derived.this[string]': type must be 'string' to match overridden member 'Base<string>.this[string]' Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[string]", "Base<string>.this[string]", "string")); } [Fact] public void TestChangeGenericIndexerParameters() { var text = @" class Base<T> { public virtual int this[string x, T y] { get { return 0; } set { } } public virtual int this[object x, T y] { get { return 0; } set { } } } class Derived : Base<string> { public override int this[string x, string y] { get { return 0; } set { } } public override int this[object x, object y] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0115: 'Derived.this[object, object]': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "this").WithArguments("Derived.this[object, object]")); } [Fact] public void TestChangeGenericEventType() { var text = @" class Base<T> { public virtual event System.Action<T> Event1 { add { } remove { } } public virtual event System.Action<T> Event2 { add { } remove { } } } class Derived : Base<string> { public override event System.Action<string> Event1 { add { } remove { } } public override event System.Action<object> Event2 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 11, Column = 49 }, //2 }); } [Fact] public void TestDoNotChangeGenericMethodReturnType() { var text = @" interface IGoo<A> { } class Base { public virtual T Method1<T>(T t) { return t; } public virtual IGoo<U> Method2<U>(U u) { return null; } } class Derived : Base { public override M Method1<M>(M t) { return t; } public override IGoo<X> Method2<X>(X u) { return null; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { }); } [Fact] public void TestClassTypeParameterReturnType() { var text = @" class Base<T> { public virtual T Property { get; set; } public virtual T Method(T t) { return t; } } class Derived<S> : Base<S> { public override S Property { get; set; } public override S Method(S s) { return s; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { }); } [Fact] public void TestNoImplementationOfAbstractMethod() { var text = @" abstract class Base { public abstract object Method1(); public abstract object Method2(); public abstract object Method3(); public abstract object Method4(int i); public abstract ref object Method5(ref object o); public abstract object Method6(ref object o); } class Derived : Base { //missed Method1 entirely public object Method2() { return null; } //missed override keyword public int Method3() { return 0; } //wrong return type public object Method4(long l) { return 0; } //wrong signature public override object Method5(ref object o) { return null; } //wrong by-value return public override ref object Method6(ref object o) { return ref o; } //wrong by-ref return } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (16,16): warning CS0114: 'Derived.Method3()' hides inherited member 'Base.Method3()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Method3() { return 0; } //wrong return type Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method3").WithArguments("Derived.Method3()", "Base.Method3()").WithLocation(16, 16), // (18,28): error CS8148: 'Derived.Method5(ref object)' must match by reference return of overridden member 'Base.Method5(ref object)' // public override object Method5(ref object o) { return null; } //wrong by-value return Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method5").WithArguments("Derived.Method5(ref object)", "Base.Method5(ref object)").WithLocation(18, 28), // (19,32): error CS8148: 'Derived.Method6(ref object)' must match by reference return of overridden member 'Base.Method6(ref object)' // public override ref object Method6(ref object o) { return ref o; } //wrong by-ref return Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Method6").WithArguments("Derived.Method6(ref object)", "Base.Method6(ref object)").WithLocation(19, 32), // (15,19): warning CS0114: 'Derived.Method2()' hides inherited member 'Base.Method2()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object Method2() { return null; } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method2").WithArguments("Derived.Method2()", "Base.Method2()").WithLocation(15, 19), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method2()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method2()").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method4(int)' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method4(int)").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method3()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method3()").WithLocation(12, 7), // (12,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Method1()' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Method1()").WithLocation(12, 7)); } [Fact] public void TestNoImplementationOfAbstractProperty() { var text = @" abstract class Base { public abstract object Property1 { get; set; } public abstract object Property2 { get; set; } public abstract object Property3 { get; set; } public abstract object Property4 { get; set; } public abstract object Property5 { get; set; } public abstract object Property6 { get; } public abstract object Property7 { get; } public abstract object Property8 { set; } public abstract object Property9 { set; } public abstract object Property10 { get; } public abstract ref object Property11 { get; } } class Derived : Base { //missed Property1 entirely public object Property2 { get; set; } //missed override keyword public override int Property3 { get; set; } //wrong type //wrong accessors public override object Property4 { get { return null; } } public override object Property5 { set { } } public override object Property6 { get; set; } public override object Property7 { set { } } public override object Property8 { get; set; } public override object Property9 { get { return null; } } //wrong by-{value,ref} return object o = null; public override ref object Property10 { get { return ref o; } } public override object Property11 { get { return null; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (23,25): error CS1715: 'Derived.Property3': type must be 'object' to match overridden member 'Base.Property3' // public override int Property3 { get; set; } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Property3").WithArguments("Derived.Property3", "Base.Property3", "object").WithLocation(23, 25), // (28,45): error CS0546: 'Derived.Property6.set': cannot override because 'Base.Property6' does not have an overridable set accessor // public override object Property6 { get; set; } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.Property6.set", "Base.Property6").WithLocation(28, 45), // (29,40): error CS0546: 'Derived.Property7.set': cannot override because 'Base.Property7' does not have an overridable set accessor // public override object Property7 { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.Property7.set", "Base.Property7").WithLocation(29, 40), // (30,40): error CS0545: 'Derived.Property8.get': cannot override because 'Base.Property8' does not have an overridable get accessor // public override object Property8 { get; set; } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.Property8.get", "Base.Property8").WithLocation(30, 40), // (31,40): error CS0545: 'Derived.Property9.get': cannot override because 'Base.Property9' does not have an overridable get accessor // public override object Property9 { get { return null; } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.Property9.get", "Base.Property9").WithLocation(31, 40), // (35,32): error CS8148: 'Derived.Property10' must match by reference return of overridden member 'Base.Property10' // public override ref object Property10 { get { return ref o; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property10").WithArguments("Derived.Property10", "Base.Property10").WithLocation(35, 32), // (36,28): error CS8148: 'Derived.Property11' must match by reference return of overridden member 'Base.Property11' // public override object Property11 { get { return null; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "Property11").WithArguments("Derived.Property11", "Base.Property11").WithLocation(36, 28), // (22,19): warning CS0114: 'Derived.Property2' hides inherited member 'Base.Property2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object Property2 { get; set; } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Property2").WithArguments("Derived.Property2", "Base.Property2").WithLocation(22, 19), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property2.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property2.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property1.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property1.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property5.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property5.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property9.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property9.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property1.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property1.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property7.get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property7.get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property3.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property3.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property2.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property2.set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Property4.set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Property4.set").WithLocation(19, 7)); } [Fact] public void TestNoImplementationOfAbstractIndexer() { var text = @" abstract class Base { public abstract object this[int w, int x, int y , int z] { get; set; } public abstract object this[int w, int x, int y , string z] { get; set; } public abstract object this[int w, int x, string y , int z] { get; set; } public abstract object this[int w, int x, string y , string z] { get; set; } public abstract object this[int w, string x, int y , int z] { get; set; } public abstract object this[int w, string x, int y , string z] { get; } public abstract object this[int w, string x, string y , int z] { get; } public abstract object this[int w, string x, string y , string z] { set; } public abstract object this[string w, int x, int y , int z] { set; } public abstract object this[string w, int x, int y, string z] { get; } public abstract ref object this[string w, int x, string y, int z] { get; } } class Derived : Base { //missed first indexer entirely public object this[int w, int x, int y , string z] { get { return 0; } set { } } //missed override keyword public override int this[int w, int x, string y , int z] { get { return 0; } set { } } //wrong type //wrong accessors public override object this[int w, int x, string y , string z] { get { return null; } } public override object this[int w, string x, int y , int z] { set { } } public override object this[int w, string x, int y , string z] { get { return 0; } set { } } public override object this[int w, string x, string y , int z] { set { } } public override object this[int w, string x, string y , string z] { get { return 0; } set { } } public override object this[string w, int x, int y , int z] { get { return null; } } //wrong by-{value,ref} return object o = null; public override ref object this[string w, int x, int y, string z] { get { return ref o; } } public override object this[string w, int x, string y, int z] { get; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (36,69): error CS0501: 'Derived.this[string, int, string, int].get' must declare a body because it is not marked abstract, extern, or partial // public override object this[string w, int x, string y, int z] { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("Derived.this[string, int, string, int].get").WithLocation(36, 69), // (23,25): error CS1715: 'Derived.this[int, int, string, int]': type must be 'object' to match overridden member 'Base.this[int, int, string, int]' // public override int this[int w, int x, string y , int z] { get { return 0; } set { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "this").WithArguments("Derived.this[int, int, string, int]", "Base.this[int, int, string, int]", "object").WithLocation(23, 25), // (28,88): error CS0546: 'Derived.this[int, string, int, string].set': cannot override because 'Base.this[int, string, int, string]' does not have an overridable set accessor // public override object this[int w, string x, int y , string z] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[int, string, int, string].set", "Base.this[int, string, int, string]").WithLocation(28, 88), // (29,70): error CS0546: 'Derived.this[int, string, string, int].set': cannot override because 'Base.this[int, string, string, int]' does not have an overridable set accessor // public override object this[int w, string x, string y , int z] { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("Derived.this[int, string, string, int].set", "Base.this[int, string, string, int]").WithLocation(29, 70), // (30,73): error CS0545: 'Derived.this[int, string, string, string].get': cannot override because 'Base.this[int, string, string, string]' does not have an overridable get accessor // public override object this[int w, string x, string y , string z] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[int, string, string, string].get", "Base.this[int, string, string, string]").WithLocation(30, 73), // (31,67): error CS0545: 'Derived.this[string, int, int, int].get': cannot override because 'Base.this[string, int, int, int]' does not have an overridable get accessor // public override object this[string w, int x, int y , int z] { get { return null; } } Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived.this[string, int, int, int].get", "Base.this[string, int, int, int]").WithLocation(31, 67), // (35,32): error CS8148: 'Derived.this[string, int, int, string]' must match by reference return of overridden member 'Base.this[string, int, int, string]' // public override ref object this[string w, int x, int y, string z] { get { return ref o; } } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[string, int, int, string]", "Base.this[string, int, int, string]").WithLocation(35, 32), // (36,28): error CS8148: 'Derived.this[string, int, string, int]' must match by reference return of overridden member 'Base.this[string, int, string, int]' // public override object this[string w, int x, string y, int z] { get; } Diagnostic(ErrorCode.ERR_CantChangeRefReturnOnOverride, "this").WithArguments("Derived.this[string, int, string, int]", "Base.this[string, int, string, int]").WithLocation(36, 28), // (22,19): warning CS0114: 'Derived.this[int, int, int, string]' hides inherited member 'Base.this[int, int, int, string]'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public object this[int w, int x, int y , string z] { get { return 0; } set { } } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "this").WithArguments("Derived.this[int, int, int, string]", "Base.this[int, int, int, string]").WithLocation(22, 19), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, string, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, string, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, string, string].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, string, string].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, int].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, string, int, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, string, int, int].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, string].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, string].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, int, int, string].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, int, int, string].get").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[string, int, int, int].set' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[string, int, int, int].set").WithLocation(19, 7), // (19,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.this[int, string, string, int].get' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.this[int, string, string, int].get").WithLocation(19, 7)); } [Fact] public void TestNoImplementationOfAbstractEvent() { var text = @" abstract class Base { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } class Derived : Base { //missed Method1 Event1 public event System.Action Event2 { add { } remove { } } //missed override keyword public override event System.Action<int> Event3 { add { } remove { } } //wrong type } "; CreateCompilation(text).VerifyDiagnostics( // (12,32): warning CS0114: 'Derived.Event2' hides inherited member 'Base.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event2 { add { } remove { } } //missed override keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (13,46): error CS1715: 'Derived.Event3': type must be 'System.Action' to match overridden member 'Base.Event3' // public override event System.Action<int> Event3 { add { } remove { } } //wrong type Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "Event3").WithArguments("Derived.Event3", "Base.Event3", "System.Action"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event2.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event2.remove"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event1.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event1.remove"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.add' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.add"), // (9,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base.Event3.remove' // class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.Event3.remove")); } [Fact] public void TestNoImplementationOfAbstractMethodFromGrandparent() { var text = @" abstract class Abstract1 { public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); } abstract class Abstract2 : Abstract1 { public override void Method1() { } public abstract void Method4(); public abstract void Method5(); } class Concrete : Abstract2 { public override void Method3() { } public override void Method5() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //Method2 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //Method4 }); } [Fact] public void TestNoImplementationOfAbstractPropertyFromGrandparent() { var text = @" abstract class Abstract1 { public abstract long Property1 { get; set; } public abstract long Property2 { get; set; } public abstract long Property3 { get; set; } } abstract class Abstract2 : Abstract1 { public override long Property1 { get; set; } public abstract long Property4 { get; set; } public abstract long Property5 { get; set; } } class Concrete : Abstract2 { public override long Property3 { get; set; } public override long Property5 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.get new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.set new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.get new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.set }); } [Fact] public void TestNoImplementationOfAbstractIndexerFromGrandparent() { var text = @" abstract class Abstract1 { public abstract long this[int x, int y, string z] { get; set; } public abstract long this[int x, string y, int z] { get; set; } public abstract long this[int x, string y, string z] { get; set; } } abstract class Abstract2 : Abstract1 { public override long this[int x, int y, string z] { get { return 0; } set { } } public abstract long this[string x, int y, int z] { get; set; } public abstract long this[string x, int y, string z] { get; set; } } class Concrete : Abstract2 { public override long this[int x, string y, string z] { get { return 0; } set { } } public override long this[string x, int y, string z] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract1.this[int, string, int].get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract1.this[int, string, int].get"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract1.this[int, string, int].set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract1.this[int, string, int].set"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract2.this[string, int, int].get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract2.this[string, int, int].get"), // (17,7): error CS0534: 'Concrete' does not implement inherited abstract member 'Abstract2.this[string, int, int].set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Concrete").WithArguments("Concrete", "Abstract2.this[string, int, int].set")); } [Fact] public void TestNoImplementationOfAbstractEventFromGrandparent() { var text = @" abstract class Abstract1 { public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; } abstract class Abstract2 : Abstract1 { public override event System.Action Event1 { add { } remove { } } public abstract event System.Action Event4; public abstract event System.Action Event5; } class Concrete : Abstract2 { public override event System.Action Event3 { add { } remove { } } public override event System.Action Event5 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.add new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //2.remove new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.add new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 17, Column = 7 }, //4.remove }); } [Fact] public void TestNoImplementationOfInterfaceMethod_01() { var text = @" interface Interface { object Method1(); object Method2(int i); ref object Method3(ref object o); object Method4(ref object o); } class Class : Interface { //missed Method1 entirely public object Method2(long l) { return 0; } //wrong signature public object Method3(ref object o) { return null; } //wrong by-value return public ref object Method4(ref object o) { return ref o; } //wrong by-ref return } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (10,15): error CS8152: 'Class' does not implement interface member 'Interface.Method4(ref object)'. 'Class.Method4(ref object)' cannot implement 'Interface.Method4(ref object)' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Method4(ref object)", "Class.Method4(ref object)").WithLocation(10, 15), // (10,15): error CS0535: 'Class' does not implement interface member 'Interface.Method2(int)' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Method2(int)").WithLocation(10, 15), // (10,15): error CS8152: 'Class' does not implement interface member 'Interface.Method3(ref object)'. 'Class.Method3(ref object)' cannot implement 'Interface.Method3(ref object)' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Method3(ref object)", "Class.Method3(ref object)").WithLocation(10, 15), // (10,15): error CS0535: 'Class' does not implement interface member 'Interface.Method1()' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Method1()").WithLocation(10, 15)); } [Fact] public void TestNoImplementationOfInterfaceMethod_02() { var source1 = @" public class C1 {} "; var comp11 = CreateCompilation(new AssemblyIdentity("lib1", new Version("4.2.1.0"), publicKeyOrToken: SigningTestHelpers.PublicKey, hasPublicKey: true), new[] { source1 }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, null).ToArray(), TestOptions.DebugDll.WithPublicSign(true)); comp11.VerifyDiagnostics(); var comp12 = CreateCompilation(new AssemblyIdentity("lib1", new Version("4.1.0.0"), publicKeyOrToken: SigningTestHelpers.PublicKey, hasPublicKey: true), new[] { source1 }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, null).ToArray(), TestOptions.DebugDll.WithPublicSign(true)); comp12.VerifyDiagnostics(); var source2 = @" public class C2 : C1 {} "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp12.EmitToImageReference() }, assemblyName: "lib2"); comp2.VerifyDiagnostics(); var source3 = @" interface I1 { void Method1(); } #pragma warning disable CS1701 class C3 : C2, #pragma warning restore CS1701 I1 { } "; var comp3 = CreateCompilation(new[] { source3 }, references: new[] { comp11.EmitToImageReference(), comp2.EmitToImageReference() }, assemblyName: "lib3"); // The unification warning shouldn't suppress the CS0535 error. comp3.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'lib2' matches identity 'lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'lib1', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib2", "lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib1").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'lib2' matches identity 'lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'lib1', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("lib1, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib2", "lib1, Version=4.2.1.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "lib1").WithLocation(1, 1), // (10,16): error CS0535: 'C3' does not implement interface member 'I1.Method1()' // I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C3", "I1.Method1()").WithLocation(10, 16) ); } [Fact] public void TestNoImplementationOfInterfaceProperty() { var text = @" interface Interface { object Property1 { get; set; } object Property2 { get; set; } object Property3 { get; set; } object Property4 { get; } object Property5 { get; } object Property6 { set; } object Property7 { set; } ref object Property8 { get; } object Property9 { get; } } class Class : Interface { //missed Property1 entirely //wrong accessors public object Property2 { get { return null; } } public object Property3 { set { } } public object Property4 { get; set; } public object Property5 { set { } } public object Property6 { get; set; } public object Property7 { get { return null; } } //wrong by-{value,ref} return object o = null; public object Property8 { get { return null; } } public ref object Property9 { get { return ref o; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property2.set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property2.set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property3.get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property3.get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property5.get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property5.get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property7.set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property7.set").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.Property8'. 'Class.Property8' cannot implement 'Interface.Property8' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Property8", "Class.Property8").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.Property9'. 'Class.Property9' cannot implement 'Interface.Property9' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.Property9", "Class.Property9").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.Property1' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.Property1").WithLocation(17, 15)); } [Fact] public void TestNoImplementationOfInterfaceIndexer() { var text = @" interface Interface { object this[int w, int x, int y, string z] { get; set; } object this[int w, int x, string y, int z] { get; set; } object this[int w, int x, string y, string z] { get; set; } object this[int w, string x, int y, int z] { get; } object this[int w, string x, int y, string z] { get; } object this[int w, string x, string y, int z] { set; } object this[int w, string x, string y, string z] { set; } ref object this[string w, int x, int y, int z] { get; } object this[string w, int x, int y, string z] { get; } } class Class : Interface { //missed first indexer entirely //wrong accessors public object this[int w, int x, string y, int z] { get { return null; } } public object this[int w, int x, string y, string z] { set { } } public object this[int w, string x, int y, int z] { get { return 0; } set { } } public object this[int w, string x, int y, string z] { set { } } public object this[int w, string x, string y, int z] { get { return 0; } set { } } public object this[int w, string x, string y, string z] { get { return null; } } // wrong by-{value,ref} return object o = null; public object this[string w, int x, int y, int z] { get { return null; } } public ref object this[string w, int x, int y, string z] { get { return ref o; } } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, string, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, string, string].set").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.this[string, int, int, int]'. 'Class.this[string, int, int, int]' cannot implement 'Interface.this[string, int, int, int]' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.this[string, int, int, int]", "Class.this[string, int, int, int]").WithLocation(17, 15), // (17,15): error CS8152: 'Class' does not implement interface member 'Interface.this[string, int, int, string]'. 'Class.this[string, int, int, string]' cannot implement 'Interface.this[string, int, int, string]' because it does not have matching return by reference. // class Class : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "Interface").WithArguments("Class", "Interface.this[string, int, int, string]", "Class.this[string, int, int, string]").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, int, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, int, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, int].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, int].set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, int, string]' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, int, string]").WithLocation(17, 15)); } [Fact] public void TestNoImplementationOfInterfaceEvent() { var text = @" interface Interface { event System.Action Event1; } class Class : Interface { //missed Event1 entirely } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 7, Column = 15 }, //1 }); } [Fact] public void TestNoImplementationOfInterfaceMethodInBase() { var text = @" interface Interface { object Method1(); object Method2(int i); } class Base : Interface { //missed Method1 entirely public object Method2(long l) { return 0; } //wrong signature } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Method2(int)' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Method2(int)").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Method1()' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Method1()").WithLocation(8, 14) ); } [Fact] public void TestNoImplementationOfBaseInterfaceMethod() { var text = @" interface Interface1 { object Method1(); } interface Interface2 { object Method2(); } class Base : Interface2 { public object Method1() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Base", "Interface2.Method2()")); } [Fact] public void TestNoImplementationOfInterfacePropertyInBase() { var text = @" interface Interface { object Property1 { get; set; } object Property2 { get; set; } } class Base : Interface { //missed Property1 entirely public long Property2 { get; set; } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.Property2'. 'Base.Property2' cannot implement 'Interface.Property2' because it does not have the matching return type of 'object'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Property2", "Base.Property2", "object").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Property1' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Property1").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.Property2'. 'Base.Property2' cannot implement 'Interface.Property2' because it does not have the matching return type of 'object'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.Property2", "Base.Property2", "object").WithLocation(18, 24) ); } [Fact] public void TestNoImplementationOfInterfaceIndexerInBase() { var text = @" interface Interface { object this[int x] { get; set; } object this[string x] { get; set; } } class Base : Interface { //missed int indexer entirely public long this[string x] { get { return 0; } set { } } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.this[string]'. 'Base.this[string]' cannot implement 'Interface.this[string]' because it does not have the matching return type of 'object'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.this[string]", "Base.this[string]", "object").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.this[int]' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.this[int]").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.this[string]'. 'Base.this[string]' cannot implement 'Interface.this[string]' because it does not have the matching return type of 'object'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.this[string]", "Base.this[string]", "object").WithLocation(18, 24) ); } [Fact] public void TestNoImplementationOfInterfaceEventInBase() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; } class Base : Interface { //missed Event1 entirely public event System.Action<int> Event2 { add { } remove { } } //wrong type } class Derived1 : Base //not declaring interface { } class Derived2 : Base, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): error CS0738: 'Base' does not implement interface member 'Interface.Event2'. 'Base.Event2' cannot implement 'Interface.Event2' because it does not have the matching return type of 'Action'. // class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Event2", "Base.Event2", "System.Action").WithLocation(8, 14), // (8,14): error CS0535: 'Base' does not implement interface member 'Interface.Event1' // class Base : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Base", "Interface.Event1").WithLocation(8, 14), // (18,24): error CS0738: 'Derived2' does not implement interface member 'Interface.Event2'. 'Base.Event2' cannot implement 'Interface.Event2' because it does not have the matching return type of 'Action'. // class Derived2 : Base, Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Derived2", "Interface.Event2", "Base.Event2", "System.Action").WithLocation(18, 24) ); } [Fact] public void TestExplicitMethodImplementation() { var text = @" interface BaseInterface { void Method4(); } interface Interface : BaseInterface { void Method1(); void Method2(); } interface Interface2 { void Method1(); } class Base : Interface { void System.Object.Method1() { } //not an interface void Base.Method1() { } //not an interface void System.Int32.Method1() { } //not an interface void Interface2.Method1() { } //does not implement Interface2 void Interface.Method3() { } //not on Interface void Interface.Method4() { } //not on Interface public void Method1() { } public void Method2() { } public void Method4() { } } class Derived : Base { void Interface.Method1() { } //does not directly list Interface } class Derived2 : Base, Interface { void Interface.Method1() { } //fine void BaseInterface.Method4() { } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (20,10): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (21,10): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (22,10): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (23,10): error CS0540: 'Base.Interface2.Method1()': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Method1()", "Interface2"), // (24,20): error CS0539: 'Base.Method3()' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method3").WithArguments("Base.Method3()"), // (25,20): error CS0539: 'Base.Method4()' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method4").WithArguments("Base.Method4()"), // (34,10): error CS0540: 'Derived.Interface.Method1()': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Method1()", "Interface")); } [Fact] public void TestExplicitPropertyImplementation() { var text = @" interface BaseInterface { int Property4 { get; } } interface Interface : BaseInterface { int Property1 { set; } int Property2 { set; } } interface Interface2 { int Property1 { set; } } class Base : Interface { int System.Object.Property1 { set { } } //not an interface int Base.Property1 { set { } } //not an interface int System.Int32.Property1 { set { } } //not an interface int Interface2.Property1 { set { } } //does not implement Interface2 int Interface.Property3 { set { } } //not on Interface int Interface.Property4 { get { return 1; } } //not on Interface public int Property1 { set { } } public int Property2 { set { } } public int Property4 { get { return 0; } } } class Derived : Base { int Interface.Property1 { set { } } //does not directly list Interface } class Derived2 : Base, Interface { int Interface.Property1 { set { } } //fine int BaseInterface.Property4 { get { return 1; } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,9): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,9): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,9): error CS0540: 'Base.Interface2.Property1': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Property1", "Interface2"), // (23,19): error CS0539: 'Base.Property3' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property3").WithArguments("Base.Property3"), // (24,19): error CS0539: 'Base.Property4' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property4").WithArguments("Base.Property4"), // (33,9): error CS0540: 'Derived.Interface.Property1': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Property1", "Interface")); } [Fact] public void TestExplicitIndexerImplementation() { var text = @" interface BaseInterface { int this[string x, string y] { get; } } interface Interface : BaseInterface { int this[int x, int y] { set; } int this[int x, string y] { set; } } interface Interface2 { int this[int x, int y] { set; } } class Base : Interface { int System.Object.this[int x, int y] { set { } } //not an interface int Base.this[int x, int y] { set { } } //not an interface int System.Int32.this[int x, int y] { set { } } //not an interface int Interface2.this[int x, int y] { set { } } //does not implement Interface2 int Interface.this[string x, int y] { set { } } //not on Interface int Interface.this[string x, string y] { get { return 1; } } //not on Interface public int this[int x, int y] { set { } } public int this[int x, string y] { set { } } public int this[string x, string y] { get { return 0; } } } class Derived : Base { int Interface.this[int x, int y] { set { } } //does not directly list Interface } class Derived2 : Base, Interface { int Interface.this[int x, int y] { set { } } //fine int BaseInterface.this[string x, string y] { get { return 1; } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0538: 'object' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,9): error CS0538: 'Base' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,9): error CS0538: 'int' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,9): error CS0540: 'Base.Interface2.this[int, int]': containing type does not implement interface 'Interface2' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.this[int, int]", "Interface2"), // (23,19): error CS0539: 'Base.this[string, int]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Base.this[string, int]"), // (24,19): error CS0539: 'Base.this[string, string]' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "this").WithArguments("Base.this[string, string]"), // (33,9): error CS0540: 'Derived.Interface.this[int, int]': containing type does not implement interface 'Interface' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.this[int, int]", "Interface")); } [Fact] public void TestExplicitEventImplementation() { var text = @" interface BaseInterface { event System.Action Event4; } interface Interface : BaseInterface { event System.Action Event1; event System.Action Event2; } interface Interface2 { event System.Action Event1; } class Base : Interface { event System.Action System.Object.Event1 { add { } remove { } } //not an interface event System.Action Base.Event1 { add { } remove { } } //not an interface event System.Action System.Int32.Event1 { add { } remove { } } //not an interface event System.Action Interface2.Event1 { add { } remove { } } //does not implement Interface2 event System.Action Interface.Event3 { add { } remove { } } //not on Interface event System.Action Interface.Event4 { add { } remove { } } //not on Interface public event System.Action Event1 { add { } remove { } } public event System.Action Event2 { add { } remove { } } public event System.Action Event4 { add { } remove { } } } class Derived : Base { event System.Action Interface.Event1 { add { } remove { } } //does not directly list Interface } class Derived2 : Base, Interface { event System.Action Interface.Event1 { add { } remove { } } //fine event System.Action BaseInterface.Event4 { add { } remove { } } //fine }"; CreateCompilation(text).VerifyDiagnostics( // (19,25): error CS0538: 'object' in explicit interface declaration is not an interface // event System.Action System.Object.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Object").WithArguments("object"), // (20,25): error CS0538: 'Base' in explicit interface declaration is not an interface // event System.Action Base.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "Base").WithArguments("Base"), // (21,25): error CS0538: 'int' in explicit interface declaration is not an interface // event System.Action System.Int32.Event1 { add { } remove { } } //not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "System.Int32").WithArguments("int"), // (22,25): error CS0540: 'Base.Interface2.Event1': containing type does not implement interface 'Interface2' // event System.Action Interface2.Event1 { add { } remove { } } //does not implement Interface2 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface2").WithArguments("Base.Interface2.Event1", "Interface2"), // (23,35): error CS0539: 'Base.Event3' in explicit interface declaration is not a member of interface // event System.Action Interface.Event3 { add { } remove { } } //not on Interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event3").WithArguments("Base.Event3"), // (24,35): error CS0539: 'Base.Event4' in explicit interface declaration is not a member of interface // event System.Action Interface.Event4 { add { } remove { } } //not on Interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Event4").WithArguments("Base.Event4"), // (33,25): error CS0540: 'Derived.Interface.Event1': containing type does not implement interface 'Interface' // event System.Action Interface.Event1 { add { } remove { } } //does not directly list Interface Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface").WithArguments("Derived.Interface.Event1", "Interface")); } [Fact] public void TestExplicitMethodImplementation2() { var text = @" public interface I<T> { void F(); } public class C : I<object> { void I<dynamic>.F() { } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,10): error CS0540: 'C.I<dynamic>.F()': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.F()", "I<dynamic>") ); } [Fact] public void TestExplicitPropertyImplementation2() { var text = @" public interface I<T> { int P { set; } } public class C : I<object> { int I<dynamic>.P { set { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,9): error CS0540: 'C.I<dynamic>.P': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.P", "I<dynamic>") ); } [Fact] public void TestExplicitIndexerImplementation2() { var text = @" public interface I<T> { int this[int x] { set; } } public class C : I<object> { int I<dynamic>.this[int x] { set { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,9): error CS0540: 'C.I<dynamic>.this[int]': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.this[int]", "I<dynamic>")); } [Fact] public void TestExplicitEventImplementation2() { var text = @" public interface I<T> { event System.Action E; } public class C : I<object> { event System.Action I<dynamic>.E { add { } remove { } } // Dev10 Error: we don't implement I<dynamic> } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,25): error CS0540: 'C.I<dynamic>.E': containing type does not implement interface 'I<dynamic>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I<dynamic>").WithArguments("C.I<dynamic>.E", "I<dynamic>") ); } [Fact] public void TestInterfaceImplementationMistakes() { var text = @" interface Interface { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); } partial class Base : Interface { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); }"; CreateCompilation(text).VerifyDiagnostics( // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method7()'. 'Base.Method7()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method7()", "Base.Method7()").WithLocation(13, 22), // (13,22): error CS0738: 'Base' does not implement interface member 'Interface.Method2()'. 'Base.Method2()' cannot implement 'Interface.Method2()' because it does not have the matching return type of 'void'. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Base", "Interface.Method2()", "Base.Method2()", "void").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method3()'. 'Base.Method3()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method3()", "Base.Method3()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method4()'. 'Base.Method4()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method4()", "Base.Method4()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method5()'. 'Base.Method5()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method5()", "Base.Method5()").WithLocation(13, 22), // (13,22): error CS0737: 'Base' does not implement interface member 'Interface.Method6()'. 'Base.Method6()' cannot implement an interface member because it is not public. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "Interface").WithArguments("Base", "Interface.Method6()", "Base.Method6()").WithLocation(13, 22), // (13,22): error CS0736: 'Base' does not implement instance interface member 'Interface.Method1()'. 'Base.Method1()' cannot implement the interface member because it is static. // partial class Base : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "Interface").WithArguments("Base", "Interface.Method1()", "Base.Method1()").WithLocation(13, 22)); } [Fact] public void TestInterfacePropertyImplementationMistakes() { var text = @" interface Interface { long Property1 { get; set; } long Property2 { get; set; } long Property3 { get; set; } long Property4 { get; set; } long Property5 { get; set; } long Property6 { get; set; } } class Base : Interface { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceIndexerImplementationMistakes() { var text = @" interface Interface { long this[int x, int y, string z] { get; set; } long this[int x, string y, int z] { get; set; } long this[int x, string y, string z] { get; set; } long this[string x, int y, int z] { get; set; } long this[string x, int y, string z] { get; set; } long this[string x, string y, int z] { get; set; } } class Base : Interface { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 14, Column = 24 }, //indexer can't be static new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceEventImplementationMistakes() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; } class Base : Interface { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, }); } [Fact] public void TestInterfaceImplementationMistakesInBase() { var text = @" interface Interface { void Method1(); void Method2(); void Method3(); void Method4(); void Method5(); void Method6(); void Method7(); } partial class Base : Interface { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } partial class Base2 { public static void Method1() { } public int Method2() { return 0; } private void Method3() { } internal void Method4() { } protected void Method5() { } protected internal void Method6() { } partial void Method7(); } class Base3 : Base2 { } class Derived : Base3, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 13, Column = 22 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 28, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 45, Column = 24 } }); } [Fact] public void TestInterfacePropertyImplementationMistakesInBase() { var text = @" interface Interface { long Property1 { get; set; } long Property2 { get; set; } long Property3 { get; set; } long Property4 { get; set; } long Property5 { get; set; } long Property6 { get; set; } } class Base : Interface { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static long Property1 { get; set; } public int Property2 { get; set; } private long Property3 { get; set; } internal long Property4 { get; set; } protected long Property5 { get; set; } protected internal long Property6 { get; set; } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, }); } [Fact] public void TestInterfaceIndexerImplementationMistakesInBase() { var text = @" interface Interface { long this[int x, int y, string z] { get; set; } long this[int x, string y, int z] { get; set; } long this[int x, string y, string z] { get; set; } long this[string x, int y, int z] { get; set; } long this[string x, int y, string z] { get; set; } long this[string x, string y, int z] { get; set; } } class Base : Interface { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static long this[int x, int y, string z] { get { return 0; } set { } } public int this[int x, string y, int z] { get { return 0; } set { } } private long this[int x, string y, string z] { get { return 0; } set { } } internal long this[string x, int y, int z] { get { return 0; } set { } } protected long this[string x, int y, string z] { get { return 0; } set { } } protected internal long this[string x, string y, int z] { get { return 0; } set { } } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 14, Column = 24 }, //indexer can't be static new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, //Base2 new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 32, Column = 24 }, //indexer can't be static }); } [Fact] public void TestInterfaceEventImplementationMistakesInBase() { var text = @" interface Interface { event System.Action Event1; event System.Action Event2; event System.Action Event3; event System.Action Event4; event System.Action Event5; event System.Action Event6; } class Base : Interface { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } class Derived1 : Base //not declaring Interface { } class Derived2 : Base, Interface { } class Base2 { public static event System.Action Event1 { add { } remove { } } public event System.Action<int> Event2 { add { } remove { } } private event System.Action Event3 { add { } remove { } } internal event System.Action Event4 { add { } remove { } } protected event System.Action Event5 { add { } remove { } } protected internal event System.Action Event6 { add { } remove { } } } class Derived3 : Base2, Interface { } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { //Base new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 12, Column = 14 }, //Derived2 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 26, Column = 24 }, //Derived3 new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 40, Column = 25 }, }); } [Fact] public void TestNewRequired() { var text = @" interface IBase { void Method1(); } interface IDerived : IBase { void Method1(); } class Base { public int field = 1; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; public int this[int x] { get { return 0; } } } class Derived : Base { public int field = 2; public int Property { get { return 0; } } public interface Interface { } public class Class { } public struct Struct { } public enum Enum { Element } public delegate void Delegate(); public event Delegate Event; public int this[int x] { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,10): warning CS0108: 'IDerived.Method1()' hides inherited member 'IBase.Method1()'. Use the new keyword if hiding was intended. // void Method1(); Diagnostic(ErrorCode.WRN_NewRequired, "Method1").WithArguments("IDerived.Method1()", "IBase.Method1()"), // (27,16): warning CS0108: 'Derived.field' hides inherited member 'Base.field'. Use the new keyword if hiding was intended. // public int field = 2; Diagnostic(ErrorCode.WRN_NewRequired, "field").WithArguments("Derived.field", "Base.field"), // (28,16): warning CS0108: 'Derived.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // public int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Property", "Base.Property"), // (29,22): warning CS0108: 'Derived.Interface' hides inherited member 'Base.Interface'. Use the new keyword if hiding was intended. // public interface Interface { } Diagnostic(ErrorCode.WRN_NewRequired, "Interface").WithArguments("Derived.Interface", "Base.Interface"), // (30,18): warning CS0108: 'Derived.Class' hides inherited member 'Base.Class'. Use the new keyword if hiding was intended. // public class Class { } Diagnostic(ErrorCode.WRN_NewRequired, "Class").WithArguments("Derived.Class", "Base.Class"), // (31,19): warning CS0108: 'Derived.Struct' hides inherited member 'Base.Struct'. Use the new keyword if hiding was intended. // public struct Struct { } Diagnostic(ErrorCode.WRN_NewRequired, "Struct").WithArguments("Derived.Struct", "Base.Struct"), // (32,17): warning CS0108: 'Derived.Enum' hides inherited member 'Base.Enum'. Use the new keyword if hiding was intended. // public enum Enum { Element } Diagnostic(ErrorCode.WRN_NewRequired, "Enum").WithArguments("Derived.Enum", "Base.Enum"), // (33,26): warning CS0108: 'Derived.Delegate' hides inherited member 'Base.Delegate'. Use the new keyword if hiding was intended. // public delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewRequired, "Delegate").WithArguments("Derived.Delegate", "Base.Delegate"), // (34,27): warning CS0108: 'Derived.Event' hides inherited member 'Base.Event'. Use the new keyword if hiding was intended. // public event Delegate Event; Diagnostic(ErrorCode.WRN_NewRequired, "Event").WithArguments("Derived.Event", "Base.Event"), // (35,16): warning CS0108: 'Derived.this[int]' hides inherited member 'Base.this[int]'. Use the new keyword if hiding was intended. // public int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewRequired, "this").WithArguments("Derived.this[int]", "Base.this[int]"), // (34,27): warning CS0067: The event 'Derived.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Derived.Event"), // (21,27): warning CS0067: The event 'Base.Event' is never used // public event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("Base.Event")); } [Fact] public void TestNewNotRequired() { var text = @" class C { //not hiding anything public new int field; public new int Property { get { return 0; } } public new interface Interface { } public new class Class { } public new struct Struct { } public new enum Enum { Element } public new delegate void Delegate(); public new event Delegate Event; public new int this[int x] { get { return 0; } } } struct S { //not hiding anything public new int field; public new int Property { get { return 0; } } public new interface Interface { } public new class Class { } public new struct Struct { } public new enum Enum { Element } public new delegate void Delegate(); public new event Delegate Event; public new int this[int x] { get { return 0; } } } interface Interface { void Method(); int Property { get; } } class D : Interface { //not required for interface impls public new void Method() { } public new int Property { get { return 0; } } } class Base : Interface { void Interface.Method() { } int Interface.Property { get { return 0; } } } class Derived : Base { //not hiding Base members because impls are explicit public new void Method() { } public new int Property { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,20): warning CS0109: The member 'C.field' does not hide an accessible member. The new keyword is not required. // public new int field; Diagnostic(ErrorCode.WRN_NewNotRequired, "field").WithArguments("C.field"), // (6,20): warning CS0109: The member 'C.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("C.Property"), // (12,31): warning CS0109: The member 'C.Event' does not hide an accessible member. The new keyword is not required. // public new event Delegate Event; Diagnostic(ErrorCode.WRN_NewNotRequired, "Event").WithArguments("C.Event"), // (7,26): warning CS0109: The member 'C.Interface' does not hide an accessible member. The new keyword is not required. // public new interface Interface { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Interface").WithArguments("C.Interface"), // (8,22): warning CS0109: The member 'C.Class' does not hide an accessible member. The new keyword is not required. // public new class Class { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Class").WithArguments("C.Class"), // (9,23): warning CS0109: The member 'C.Struct' does not hide an accessible member. The new keyword is not required. // public new struct Struct { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Struct").WithArguments("C.Struct"), // (10,21): warning CS0109: The member 'C.Enum' does not hide an accessible member. The new keyword is not required. // public new enum Enum { Element } Diagnostic(ErrorCode.WRN_NewNotRequired, "Enum").WithArguments("C.Enum"), // (11,30): warning CS0109: The member 'C.Delegate' does not hide an accessible member. The new keyword is not required. // public new delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewNotRequired, "Delegate").WithArguments("C.Delegate"), // (13,20): warning CS0109: The member 'C.this[int]' does not hide an accessible member. The new keyword is not required. // public new int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "this").WithArguments("C.this[int]"), // (19,20): warning CS0109: The member 'S.field' does not hide an accessible member. The new keyword is not required. // public new int field; Diagnostic(ErrorCode.WRN_NewNotRequired, "field").WithArguments("S.field"), // (20,20): warning CS0109: The member 'S.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("S.Property"), // (26,31): warning CS0109: The member 'S.Event' does not hide an accessible member. The new keyword is not required. // public new event Delegate Event; Diagnostic(ErrorCode.WRN_NewNotRequired, "Event").WithArguments("S.Event"), // (21,26): warning CS0109: The member 'S.Interface' does not hide an accessible member. The new keyword is not required. // public new interface Interface { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Interface").WithArguments("S.Interface"), // (22,22): warning CS0109: The member 'S.Class' does not hide an accessible member. The new keyword is not required. // public new class Class { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Class").WithArguments("S.Class"), // (23,23): warning CS0109: The member 'S.Struct' does not hide an accessible member. The new keyword is not required. // public new struct Struct { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Struct").WithArguments("S.Struct"), // (24,21): warning CS0109: The member 'S.Enum' does not hide an accessible member. The new keyword is not required. // public new enum Enum { Element } Diagnostic(ErrorCode.WRN_NewNotRequired, "Enum").WithArguments("S.Enum"), // (25,30): warning CS0109: The member 'S.Delegate' does not hide an accessible member. The new keyword is not required. // public new delegate void Delegate(); Diagnostic(ErrorCode.WRN_NewNotRequired, "Delegate").WithArguments("S.Delegate"), // (27,20): warning CS0109: The member 'S.this[int]' does not hide an accessible member. The new keyword is not required. // public new int this[int x] { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "this").WithArguments("S.this[int]"), // (39,21): warning CS0109: The member 'D.Method()' does not hide an accessible member. The new keyword is not required. // public new void Method() { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("D.Method()"), // (40,20): warning CS0109: The member 'D.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("D.Property"), // (52,21): warning CS0109: The member 'Derived.Method()' does not hide an accessible member. The new keyword is not required. // public new void Method() { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived.Method()"), // (53,20): warning CS0109: The member 'Derived.Property' does not hide an accessible member. The new keyword is not required. // public new int Property { get { return 0; } } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("Derived.Property"), // (5,20): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value 0 // public new int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "0"), // (26,31): warning CS0067: The event 'S.Event' is never used // public new event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("S.Event"), // (19,20): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value 0 // public new int field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "0"), // (12,31): warning CS0067: The event 'C.Event' is never used // public new event Delegate Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("C.Event") ); } [Fact] public void TestNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract void Method1(); public abstract void Method2(); public abstract void Method3(); //for virtual case in Derived public virtual void Method4() { } public virtual void Method5() { } public virtual void Method6() { } //for override case in Derived2 public virtual void Method7() { } public virtual void Method8() { } public virtual void Method9() { } //for grandparent case in Derived2 public virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } } abstract class Derived : Base { //abstract -> * public void Method1() { } public abstract void Method2(); public virtual void Method3() { } //virtual -> * public void Method4() { } public abstract void Method5(); public virtual void Method6() { } //for override case in Derived2 public override void Method7() { } public override void Method8() { } public override void Method9() { } } abstract class Derived2 : Derived { //override -> * public void Method7() { } public abstract void Method8(); public virtual void Method9() { } //grandparent case public void Method10() { } public abstract void Method11(); public virtual void Method12() { } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, }); } [Fact] public void TestPropertyNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract long Property1 { get; set; } public abstract long Property2 { get; set; } public abstract long Property3 { get; set; } //for virtual case in Derived public virtual long Property4 { get; set; } public virtual long Property5 { get; set; } public virtual long Property6 { get; set; } //for override case in Derived2 public virtual long Property7 { get; set; } public virtual long Property8 { get; set; } public virtual long Property9 { get; set; } //for grandparent case in Derived2 public virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } } abstract class Derived : Base { //abstract -> * public long Property1 { get; set; } public abstract long Property2 { get; set; } public virtual long Property3 { get; set; } //virtual -> * public long Property4 { get; set; } public abstract long Property5 { get; set; } public virtual long Property6 { get; set; } //for override case in Derived2 public override long Property7 { get; set; } public override long Property8 { get; set; } public override long Property9 { get; set; } } abstract class Derived2 : Derived { //override -> * public long Property7 { get; set; } public abstract long Property8 { get; set; } public virtual long Property9 { get; set; } //grandparent case public long Property10 { get; set; } public abstract long Property11 { get; set; } public virtual long Property12 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, //1.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, //2.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, //3.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, //4 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, //5 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, //6 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, //7 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, //8 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, //9 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, //10 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, //11 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, //12 }); } [Fact] public void TestIndexerNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract long this[int w, int x, int y, string z] { get; set; } public abstract long this[int w, int x, string y, int z] { get; set; } public abstract long this[int w, int x, string y, string z] { get; set; } //for virtual case in Derived public virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } public virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } //for override case in Derived2 public virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } //for grandparent case in Derived2 public virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } } abstract class Derived : Base { //abstract -> * public long this[int w, int x, int y, string z] { get { return 0; } set { } } public abstract long this[int w, int x, string y, int z] { get; set; } public virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } //virtual -> * public long this[int w, string x, int y, int z] { get { return 0; } set { } } public abstract long this[int w, string x, int y, string z] { get; set; } public virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } //for override case in Derived2 public override long this[int w, string x, string y, string z] { get { return 0; } set { } } public override long this[string w, int x, int y, int z] { get { return 0; } set { } } public override long this[string w, int x, int y, string z] { get { return 0; } set { } } } abstract class Derived2 : Derived { //override -> * public long this[int w, string x, string y, string z] { get { return 0; } set { } } public abstract long this[string w, int x, int y, int z] { get; set; } public virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } //grandparent case public long this[string w, int x, string y, int z] { get { return 0; } set { } } public abstract long this[string w, int x, string y, string z] { get; set; } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 28, Column = 17, IsWarning = true }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 28, Column = 17, IsWarning = false }, //1.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 29, Column = 26, IsWarning = true }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 29, Column = 26, IsWarning = false }, //2.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 30, Column = 25, IsWarning = true }, //3 new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 30, Column = 25, IsWarning = false }, //3.get/set new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 33, Column = 17, IsWarning = true }, //4 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 34, Column = 26, IsWarning = true }, //5 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 35, Column = 25, IsWarning = true }, //6 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 46, Column = 17, IsWarning = true }, //7 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 47, Column = 26, IsWarning = true }, //8 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 48, Column = 25, IsWarning = true }, //9 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 51, Column = 17, IsWarning = true }, //10 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 52, Column = 26, IsWarning = true }, //11 new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 53, Column = 25, IsWarning = true }, //12 }); } [Fact] public void TestEventNewOrOverrideRequired() { var text = @" abstract class Base { //for abstract case in Derived public abstract event System.Action Event1; public abstract event System.Action Event2; public abstract event System.Action Event3; //for virtual case in Derived public virtual event System.Action Event4 { add { } remove { } } public virtual event System.Action Event5 { add { } remove { } } public virtual event System.Action Event6 { add { } remove { } } //for override case in Derived2 public virtual event System.Action Event7 { add { } remove { } } public virtual event System.Action Event8 { add { } remove { } } public virtual event System.Action Event9 { add { } remove { } } //for grandparent case in Derived2 public virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } } abstract class Derived : Base { //abstract -> * public event System.Action Event1 { add { } remove { } } public abstract event System.Action Event2; public virtual event System.Action Event3 { add { } remove { } } //virtual -> * public event System.Action Event4 { add { } remove { } } public abstract event System.Action Event5; public virtual event System.Action Event6 { add { } remove { } } //for override case in Derived2 public override event System.Action Event7 { add { } remove { } } public override event System.Action Event8 { add { } remove { } } public override event System.Action Event9 { add { } remove { } } } abstract class Derived2 : Derived { //override -> * public event System.Action Event7 { add { } remove { } } public abstract event System.Action Event8; public virtual event System.Action Event9 { add { } remove { } } //grandparent case public event System.Action Event10 { add { } remove { } } public abstract event System.Action Event11; public virtual event System.Action Event12 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (28,32): error CS0533: 'Derived.Event1' hides inherited abstract member 'Base.Event1' // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event1").WithArguments("Derived.Event1", "Base.Event1"), // (28,32): warning CS0114: 'Derived.Event1' hides inherited member 'Base.Event1'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event1 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event1").WithArguments("Derived.Event1", "Base.Event1"), // (29,41): error CS0533: 'Derived.Event2' hides inherited abstract member 'Base.Event2' // public abstract event System.Action Event2; Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (29,41): warning CS0114: 'Derived.Event2' hides inherited member 'Base.Event2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event2; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event2").WithArguments("Derived.Event2", "Base.Event2"), // (30,40): error CS0533: 'Derived.Event3' hides inherited abstract member 'Base.Event3' // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Event3").WithArguments("Derived.Event3", "Base.Event3"), // (30,40): warning CS0114: 'Derived.Event3' hides inherited member 'Base.Event3'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event3 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event3").WithArguments("Derived.Event3", "Base.Event3"), // (33,32): warning CS0114: 'Derived.Event4' hides inherited member 'Base.Event4'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event4 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event4").WithArguments("Derived.Event4", "Base.Event4"), // (34,41): warning CS0114: 'Derived.Event5' hides inherited member 'Base.Event5'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event5; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event5").WithArguments("Derived.Event5", "Base.Event5"), // (35,40): warning CS0114: 'Derived.Event6' hides inherited member 'Base.Event6'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event6 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event6").WithArguments("Derived.Event6", "Base.Event6"), // (46,32): warning CS0114: 'Derived2.Event7' hides inherited member 'Derived.Event7'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event7 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event7").WithArguments("Derived2.Event7", "Derived.Event7"), // (47,41): warning CS0114: 'Derived2.Event8' hides inherited member 'Derived.Event8'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event8; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event8").WithArguments("Derived2.Event8", "Derived.Event8"), // (48,40): warning CS0114: 'Derived2.Event9' hides inherited member 'Derived.Event9'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event9 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event9").WithArguments("Derived2.Event9", "Derived.Event9"), // (51,32): warning CS0114: 'Derived2.Event10' hides inherited member 'Base.Event10'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public event System.Action Event10 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event10").WithArguments("Derived2.Event10", "Base.Event10"), // (52,41): warning CS0114: 'Derived2.Event11' hides inherited member 'Base.Event11'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public abstract event System.Action Event11; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event11").WithArguments("Derived2.Event11", "Base.Event11"), // (53,40): warning CS0114: 'Derived2.Event12' hides inherited member 'Base.Event12'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public virtual event System.Action Event12 { add { } remove { } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Event12").WithArguments("Derived2.Event12", "Base.Event12")); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod() { var text = @" public interface Interface<T> { void Method(int i); void Method(T i); } public class Class : Interface<int> { void Interface<int>.Method(int i) { } //this explicitly implements both methods in Interface<int> public void Method(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 10, Column = 25, IsWarning = true }, }); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethodWithDifferingConstraints() { var text = @" public interface Interface<T> { void Method<V>(int i) where V : new(); void Method<V>(T i); } public class Class : Interface<int> { void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): warning CS0473: Explicit interface implementation 'Class.Interface<int>.Method<V>(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<int>.Method<V>(int)").WithLocation(10, 25)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethodWithDifferingConstraints_OppositeDeclarationOrder() { var text = @" public interface Interface<T> { void Method<V>(T i); void Method<V>(int i) where V : new(); } public class Class : Interface<int> { void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): warning CS0473: Explicit interface implementation 'Class.Interface<int>.Method<V>(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<int>.Method<V>(int)").WithLocation(10, 25), // (10,48): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint // void Interface<int>.Method<V>(int i) { _ = new V(); } //this explicitly implements both methods in Interface<int> Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(10, 48), // (11,17): error CS0425: The constraints for type parameter 'V' of method 'Class.Method<V>(int)' must match the constraints for type parameter 'V' of interface method 'Interface<int>.Method<V>(int)'. Consider using an explicit interface implementation instead. // public void Method<V>(int i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Method").WithArguments("V", "Class.Method<V>(int)", "V", "Interface<int>.Method<V>(int)").WithLocation(11, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceIndexer() { var text = @" public interface Interface<T> { long this[int i] { set; } long this[T i] { set; } } public class Class : Interface<int> { long Interface<int>.this[int i] { set { } } //this explicitly implements both methods in Interface<int> public long this[int i] { set { } } //this is here to avoid CS0535 - not implementing interface method } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 10, Column = 25, IsWarning = true }, }); } [Fact] public void TestAmbiguousImplementationMethod() { var text = @" public interface Interface<T, U> { void Method(int i); void Method(T i); void Method(U i); } public class Base<T> : Interface<T, T> { public void Method(int i) { } public void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class Other : Interface<int, int> { void Interface<int, int>.Method(int i) { } } class YetAnother : Interface<int, int> { public void Method(int i) { } } "; //Both Base methods implement Interface.Method(int) //Both Base methods implement Interface.Method(T) //Both Base methods implement Interface.Method(U) CreateCompilation(text).VerifyDiagnostics( // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.Method(int)' implements interface member 'Interface<int, int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.Method(int)", "Interface<int, int>.Method(int)", "Derived").WithLocation(15, 35), // (19,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(19, 15), // (19,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(19, 15), // (21,30): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(21, 30) ); } [Fact] public void TestAmbiguousImplementationIndexer() { var text = @" public interface Interface<T, U> { long this[int i] { set; } long this[T i] { set; } long this[U i] { set; } } public class Base<T> : Interface<T, T> { public long this[int i] { set { } } public long this[T i] { set { } } } public class Derived : Base<int>, Interface<int, int> { } "; // CONSIDER: Dev10 doesn't report these warnings - not sure why CreateCompilation(text).VerifyDiagnostics( // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35), // (15,35): warning CS1956: Member 'Base<int>.this[int]' implements interface member 'Interface<int, int>.this[int]' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // public class Derived : Base<int>, Interface<int, int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int, int>").WithArguments("Base<int>.this[int]", "Interface<int, int>.this[int]", "Derived").WithLocation(15, 35)); } [Fact] public void TestHideAmbiguousImplementationMethod() { var text = @" public interface Interface<T, U> { void Method(int i); void Method(T i); void Method(U i); } public class Base<T> : Interface<T, T> { public void Method(int i) { } public void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { public new void Method(int i) { } //overrides Base's interface mapping } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousImplementationIndexer() { var text = @" public interface Interface<T, U> { long this[int i] { set; } long this[T i] { set; } long this[U i] { set; } } public class Base<T> : Interface<T, T> { public long this[int i] { set { } } public long this[T i] { set { } } } public class Derived : Base<int>, Interface<int, int> { public new long this[int i] { set { } } //overrides Base's interface mapping } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousOverridesMethod() { var text = @" public class Base<T, U> { public virtual void Method(int i) { } public virtual void Method(T i) { } public virtual void Method(U i) { } } public class Derived : Base<int, int> { public new virtual void Method(int i) { } } public class Derived2 : Derived { public override void Method(int i) { base.Method(i); } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestHideAmbiguousOverridesIndexer() { var text = @" public class Base<T, U> { public virtual long this[int i] { set { } } public virtual long this[T i] { set { } } public virtual long this[U i] { set { } } } public class Derived : Base<int, int> { public new virtual long this[int i] { set { } } } public class Derived2 : Derived { public override long this[int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void TestAmbiguousOverrideMethod() { var text = @" public class Base<TShort, TInt> { public virtual void Method(TShort s, int i) { } public virtual void Method(short s, TInt i) { } } public class Derived : Base<short, int> { public override void Method(short s, int i) { } } "; CSharpCompilation comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.Method(TShort, int)' and 'Base<TShort, TInt>.Method(short, TInt)' have the same signature in type 'Derived', so they cannot be overridden // public override void Method(short s, int i) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "Method").WithArguments("Base<TShort, TInt>.Method(TShort, int)", "Base<TShort, TInt>.Method(short, TInt)", "Derived").WithLocation(10, 26) ); } else { comp.VerifyDiagnostics( // (4,25): warning CS1957: Member 'Derived.Method(short, int)' overrides 'Base<short, int>.Method(short, int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Method(TShort s, int i) { } Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Method").WithArguments("Base<short, int>.Method(short, int)", "Derived.Method(short, int)").WithLocation(4, 25), // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.Method(TShort, int)' and 'Base<TShort, TInt>.Method(short, TInt)' have the same signature in type 'Derived', so they cannot be overridden // public override void Method(short s, int i) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "Method").WithArguments("Base<TShort, TInt>.Method(TShort, int)", "Base<TShort, TInt>.Method(short, TInt)", "Derived").WithLocation(10, 26) ); } } [Fact] public void TestAmbiguousOverrideIndexer() { var text = @" public class Base<TShort, TInt> { public virtual long this[TShort s, int i] { set { } } public virtual long this[short s, TInt i] { set { } } } public class Derived : Base<short, int> { public override long this[short s, int i] { set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0462: The inherited members 'Base<TShort, TInt>.this[TShort, int]' and 'Base<TShort, TInt>.this[short, TInt]' have the same signature in type 'Derived', so they cannot be overridden Diagnostic(ErrorCode.ERR_AmbigOverride, "this").WithArguments("Base<TShort, TInt>.this[TShort, int]", "Base<TShort, TInt>.this[short, TInt]", "Derived")); } [Fact] public void TestRuntimeAmbiguousOverride() { var text = @" class Base<TInt> { //these signatures differ only in ref/out public virtual void Method(int @in, ref int @ref) { } public virtual void Method(TInt @in, out TInt @out) { @out = @in; } } class Derived : Base<int> { public override void Method(int @in, ref int @ref) { } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, compilation.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (compilation.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { // We no longer report a runtime ambiguous override because the compiler // produces a methodimpl record to disambiguate. compilation.VerifyDiagnostics( ); } else { compilation.VerifyDiagnostics( // (5,25): warning CS1957: Member 'Derived.Method(int, ref int)' overrides 'Base<int>.Method(int, ref int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Method(int @in, ref int @ref) { } Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Method").WithArguments("Base<int>.Method(int, ref int)", "Derived.Method(int, ref int)").WithLocation(5, 25) ); } } [Fact] public void TestOverrideInaccessibleMethod() { var text1 = @" public class Base { internal virtual void Method() {} } "; var text2 = @" public class Derived : Base { internal override void Method() { } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleProperty() { var text1 = @" public class Base { internal virtual long Property { get; set; } } "; var text2 = @" public class Derived : Base { internal override long Property { get; set; } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleIndexer() { var text1 = @" public class Base { internal virtual long this[int x] { get { return 0; } set { } } } "; var text2 = @" public class Derived : Base { internal override long this[int x] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 28 }, //can't see internal method in other compilation }); } [Fact] public void TestOverrideInaccessibleEvent() { var text1 = @" public class Base { internal virtual event System.Action Event { add { } remove { } } } "; var text2 = @" public class Derived : Base { internal override event System.Action Event { add { } remove { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 4, Column = 43 }, //can't see internal method in other compilation }); } [Fact] public void TestVirtualMethodAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual void Method1() { } internal virtual void Method2() { } internal virtual void Method3() { } protected virtual void Method4() { } protected virtual void Method5() { } protected virtual void Method6() { } protected internal virtual void Method7() { } protected internal virtual void Method8() { } protected internal virtual void Method9() { } protected internal virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } public virtual void Method13() { } private protected virtual void Method14() { } private protected virtual void Method15() { } private protected virtual void Method16() { } private protected virtual void Method17() { } } public class Derived1 : Base { protected override void Method1() { } protected internal override void Method2() { } public override void Method3() { } internal override void Method4() { } protected internal override void Method5() { } public override void Method6() { } internal override void Method7() { } protected override void Method8() { } protected internal override void Method9() { } //correct public override void Method10() { } internal override void Method11() { } protected override void Method12() { } protected internal override void Method13() { } internal override void Method14() { } protected override void Method15() { } protected internal override void Method16() { } public override void Method17() { } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (30,38): error CS0507: 'Derived1.Method2()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method2()' // protected internal override void Method2() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method2").WithArguments("Derived1.Method2()", "internal", "Base.Method2()").WithLocation(30, 38), // (31,26): error CS0507: 'Derived1.Method3()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method3()' // public override void Method3() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method3").WithArguments("Derived1.Method3()", "internal", "Base.Method3()").WithLocation(31, 26), // (33,28): error CS0507: 'Derived1.Method4()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method4()' // internal override void Method4() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method4").WithArguments("Derived1.Method4()", "protected", "Base.Method4()").WithLocation(33, 28), // (34,38): error CS0507: 'Derived1.Method5()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method5()' // protected internal override void Method5() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method5").WithArguments("Derived1.Method5()", "protected", "Base.Method5()").WithLocation(34, 38), // (35,26): error CS0507: 'Derived1.Method6()': cannot change access modifiers when overriding 'protected' inherited member 'Base.Method6()' // public override void Method6() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method6").WithArguments("Derived1.Method6()", "protected", "Base.Method6()").WithLocation(35, 26), // (37,28): error CS0507: 'Derived1.Method7()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method7()' // internal override void Method7() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method7").WithArguments("Derived1.Method7()", "protected internal", "Base.Method7()").WithLocation(37, 28), // (38,29): error CS0507: 'Derived1.Method8()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method8()' // protected override void Method8() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method8").WithArguments("Derived1.Method8()", "protected internal", "Base.Method8()").WithLocation(38, 29), // (40,26): error CS0507: 'Derived1.Method10()': cannot change access modifiers when overriding 'protected internal' inherited member 'Base.Method10()' // public override void Method10() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method10").WithArguments("Derived1.Method10()", "protected internal", "Base.Method10()").WithLocation(40, 26), // (42,28): error CS0507: 'Derived1.Method11()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method11()' // internal override void Method11() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method11").WithArguments("Derived1.Method11()", "public", "Base.Method11()").WithLocation(42, 28), // (43,29): error CS0507: 'Derived1.Method12()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method12()' // protected override void Method12() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method12").WithArguments("Derived1.Method12()", "public", "Base.Method12()").WithLocation(43, 29), // (44,38): error CS0507: 'Derived1.Method13()': cannot change access modifiers when overriding 'public' inherited member 'Base.Method13()' // protected internal override void Method13() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method13").WithArguments("Derived1.Method13()", "public", "Base.Method13()").WithLocation(44, 38), // (46,28): error CS0507: 'Derived1.Method14()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method14()' // internal override void Method14() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method14").WithArguments("Derived1.Method14()", "private protected", "Base.Method14()").WithLocation(46, 28), // (47,29): error CS0507: 'Derived1.Method15()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method15()' // protected override void Method15() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method15").WithArguments("Derived1.Method15()", "private protected", "Base.Method15()").WithLocation(47, 29), // (48,38): error CS0507: 'Derived1.Method16()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method16()' // protected internal override void Method16() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method16").WithArguments("Derived1.Method16()", "private protected", "Base.Method16()").WithLocation(48, 38), // (49,26): error CS0507: 'Derived1.Method17()': cannot change access modifiers when overriding 'private protected' inherited member 'Base.Method17()' // public override void Method17() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method17").WithArguments("Derived1.Method17()", "private protected", "Base.Method17()").WithLocation(49, 26), // (29,29): error CS0507: 'Derived1.Method1()': cannot change access modifiers when overriding 'internal' inherited member 'Base.Method1()' // protected override void Method1() { } Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "Method1").WithArguments("Derived1.Method1()", "internal", "Base.Method1()").WithLocation(29, 29) ); } [Fact] public void TestVirtualPropertyAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual long Property1 { get; set; } internal virtual long Property2 { get; set; } internal virtual long Property3 { get; set; } protected virtual long Property4 { get; set; } protected virtual long Property5 { get; set; } protected virtual long Property6 { get; set; } protected internal virtual long Property7 { get; set; } protected internal virtual long Property8 { get; set; } protected internal virtual long Property9 { get; set; } protected internal virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } public virtual long Property13 { get; set; } } public class Derived1 : Base { protected override long Property1 { get; set; } protected internal override long Property2 { get; set; } public override long Property3 { get; set; } internal override long Property4 { get; set; } protected internal override long Property5 { get; set; } public override long Property6 { get; set; } internal override long Property7 { get; set; } protected override long Property8 { get; set; } protected internal override long Property9 { get; set; } //correct public override long Property10 { get; set; } internal override long Property11 { get; set; } protected override long Property12 { get; set; } protected internal override long Property13 { get; set; } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 38 }, }); } [Fact] public void TestVirtualIndexerAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual long this[int w, int x, int y, string z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, int z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } protected internal virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, string z] { get { return 0; } set { } } } public class Derived1 : Base { protected override long this[int w, int x, int y, string z] { get { return 0; } set { } } protected internal override long this[int w, int x, string y, int z] { get { return 0; } set { } } public override long this[int w, int x, string y, string z] { get { return 0; } set { } } internal override long this[int w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[int w, string x, int y, string z] { get { return 0; } set { } } public override long this[int w, string x, string y, int z] { get { return 0; } set { } } internal override long this[int w, string x, string y, string z] { get { return 0; } set { } } protected override long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, int x, int y, string z] { get { return 0; } set { } } //correct public override long this[string w, int x, string y, int z] { get { return 0; } set { } } internal override long this[string w, int x, string y, string z] { get { return 0; } set { } } protected override long this[string w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 38 }, }); } [Fact] public void TestVirtualEventAccessibilityWithinAssembly() { var text = @" public class Base { internal virtual event System.Action Event1 { add { } remove { } } internal virtual event System.Action Event2 { add { } remove { } } internal virtual event System.Action Event3 { add { } remove { } } protected virtual event System.Action Event4 { add { } remove { } } protected virtual event System.Action Event5 { add { } remove { } } protected virtual event System.Action Event6 { add { } remove { } } protected internal virtual event System.Action Event7 { add { } remove { } } protected internal virtual event System.Action Event8 { add { } remove { } } protected internal virtual event System.Action Event9 { add { } remove { } } protected internal virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } public virtual event System.Action Event13 { add { } remove { } } } public class Derived1 : Base { protected override event System.Action Event1 { add { } remove { } } protected internal override event System.Action Event2 { add { } remove { } } public override event System.Action Event3 { add { } remove { } } internal override event System.Action Event4 { add { } remove { } } protected internal override event System.Action Event5 { add { } remove { } } public override event System.Action Event6 { add { } remove { } } internal override event System.Action Event7 { add { } remove { } } protected override event System.Action Event8 { add { } remove { } } protected internal override event System.Action Event9 { add { } remove { } } //correct public override event System.Action Event10 { add { } remove { } } internal override event System.Action Event11 { add { } remove { } } protected override event System.Action Event12 { add { } remove { } } protected internal override event System.Action Event13 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 24, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 25, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 26, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 28, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 29, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 30, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 32, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 33, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 35, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 37, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 38, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 39, Column = 53 }, }); } [WorkItem(540185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540185")] [Fact] public void TestChangeVirtualPropertyAccessorAccessibilityWithinAssembly() { var text = @" public class Base { public virtual long Property1 { get; protected set; } } public class Derived1 : Base { public override long Property1 { get; private set; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "set").WithArguments("Derived1.Property1.set", "protected", "Base.Property1.set")); } [Fact] public void TestChangeVirtualIndexerAccessorAccessibilityWithinAssembly() { var text = @" public class Base { public virtual long this[int x] { get { return 0; } protected set { } } } public class Derived1 : Base { public override long this[int x] { get { return 0; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,66): error CS0507: 'Derived1.this[int].set': cannot change access modifiers when overriding 'protected' inherited member 'Base.this[int].set' Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "set").WithArguments("Derived1.this[int].set", "protected", "Base.this[int].set")); } [Fact] public void TestVirtualMethodAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual void Method1() { } internal virtual void Method2() { } internal virtual void Method3() { } protected virtual void Method4() { } protected virtual void Method5() { } protected virtual void Method6() { } protected internal virtual void Method7() { } protected internal virtual void Method8() { } protected internal virtual void Method9() { } protected internal virtual void Method10() { } public virtual void Method11() { } public virtual void Method12() { } public virtual void Method13() { } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override void Method1() { } protected internal override void Method2() { } public override void Method3() { } internal override void Method4() { } protected internal override void Method5() { } public override void Method6() { } //protected internal in another assembly is protected in this one internal override void Method7() { } protected override void Method8() { } //correct protected internal override void Method9() { } public override void Method10() { } internal override void Method11() { } protected override void Method12() { } protected internal override void Method13() { } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualPropertyAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual long Property1 { get; set; } internal virtual long Property2 { get; set; } internal virtual long Property3 { get; set; } protected virtual long Property4 { get; set; } protected virtual long Property5 { get; set; } protected virtual long Property6 { get; set; } protected internal virtual long Property7 { get; set; } protected internal virtual long Property8 { get; set; } protected internal virtual long Property9 { get; set; } protected internal virtual long Property10 { get; set; } public virtual long Property11 { get; set; } public virtual long Property12 { get; set; } public virtual long Property13 { get; set; } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override long Property1 { get; set; } protected internal override long Property2 { get; set; } public override long Property3 { get; set; } internal override long Property4 { get; set; } protected internal override long Property5 { get; set; } public override long Property6 { get; set; } //protected internal in another assembly is protected in this one internal override long Property7 { get; set; } protected override long Property8 { get; set; } //correct protected internal override long Property9 { get; set; } public override long Property10 { get; set; } internal override long Property11 { get; set; } protected override long Property12 { get; set; } protected internal override long Property13 { get; set; } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualIndexerAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual long this[int w, int x, int y, string z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, int z] { get { return 0; } set { } } internal virtual long this[int w, int x, string y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, int z] { get { return 0; } set { } } protected virtual long this[int w, string x, int y, string z] { get { return 0; } set { } } protected virtual long this[int w, string x, string y, int z] { get { return 0; } set { } } protected internal virtual long this[int w, string x, string y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, int z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, int y, string z] { get { return 0; } set { } } protected internal virtual long this[string w, int x, string y, int z] { get { return 0; } set { } } public virtual long this[string w, int x, string y, string z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, int z] { get { return 0; } set { } } public virtual long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override long this[int w, int x, int y, string z] { get { return 0; } set { } } protected internal override long this[int w, int x, string y, int z] { get { return 0; } set { } } public override long this[int w, int x, string y, string z] { get { return 0; } set { } } internal override long this[int w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[int w, string x, int y, string z] { get { return 0; } set { } } public override long this[int w, string x, string y, int z] { get { return 0; } set { } } //protected internal in another assembly is protected in this one internal override long this[int w, string x, string y, string z] { get { return 0; } set { } } protected override long this[string w, int x, int y, int z] { get { return 0; } set { } } //correct protected internal override long this[string w, int x, int y, string z] { get { return 0; } set { } } public override long this[string w, int x, string y, int z] { get { return 0; } set { } } internal override long this[string w, int x, string y, string z] { get { return 0; } set { } } protected override long this[string w, string x, int y, int z] { get { return 0; } set { } } protected internal override long this[string w, string x, int y, string z] { get { return 0; } set { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 38 }, }); } [Fact] public void TestVirtualEventAccessibilityAcrossAssemblies() { var text1 = @" public class Base { internal virtual event System.Action Event1 { add { } remove { } } internal virtual event System.Action Event2 { add { } remove { } } internal virtual event System.Action Event3 { add { } remove { } } protected virtual event System.Action Event4 { add { } remove { } } protected virtual event System.Action Event5 { add { } remove { } } protected virtual event System.Action Event6 { add { } remove { } } protected internal virtual event System.Action Event7 { add { } remove { } } protected internal virtual event System.Action Event8 { add { } remove { } } protected internal virtual event System.Action Event9 { add { } remove { } } protected internal virtual event System.Action Event10 { add { } remove { } } public virtual event System.Action Event11 { add { } remove { } } public virtual event System.Action Event12 { add { } remove { } } public virtual event System.Action Event13 { add { } remove { } } } "; var text2 = @" public class Derived2 : Base { //can't find to override protected override event System.Action Event1 { add { } remove { } } protected internal override event System.Action Event2 { add { } remove { } } public override event System.Action Event3 { add { } remove { } } internal override event System.Action Event4 { add { } remove { } } protected internal override event System.Action Event5 { add { } remove { } } public override event System.Action Event6 { add { } remove { } } //protected internal in another assembly is protected in this one internal override event System.Action Event7 { add { } remove { } } protected override event System.Action Event8 { add { } remove { } } //correct protected internal override event System.Action Event9 { add { } remove { } } public override event System.Action Event10 { add { } remove { } } internal override event System.Action Event11 { add { } remove { } } protected override event System.Action Event12 { add { } remove { } } protected internal override event System.Action Event13 { add { } remove { } } } "; CompileAndVerifyDiagnostics(text1, text2, Array.Empty<ErrorDescription>(), new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 5, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 6, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 7, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 9, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 10, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 11, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 14, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 16, Column = 53 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 17, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 19, Column = 43 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 20, Column = 44 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 21, Column = 53 }, }); } [Fact] public void TestExplicitPropertyChangeAccessors() { var text = @" interface Interface { int Property1 { get; set; } int Property2 { get; set; } int Property3 { get; set; } int Property4 { get; } int Property5 { get; } int Property6 { get; } int Property7 { set; } int Property8 { set; } int Property9 { set; } } class Class : Interface { int Interface.Property1 { get { return 1; } } int Interface.Property2 { set { } } int Interface.Property3 { get { return 1; } set { } } int Interface.Property4 { get { return 1; } } int Interface.Property5 { set { } } int Interface.Property6 { get { return 1; } set { } } int Interface.Property7 { get { return 1; } } int Interface.Property8 { set { } } int Interface.Property9 { get { return 1; } set { } } } "; CompileAndVerifyDiagnostics(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 19, Column = 19 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 20, Column = 19 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 24, Column = 19 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 24, Column = 31 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 25, Column = 49 }, //5 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 27, Column = 19 }, //7 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 27, Column = 31 }, //7 new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 29, Column = 31 }, //9 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //1 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //2 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //4 new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 17, Column = 15 }, //7 }); } [Fact] public void TestExplicitIndexerChangeAccessors() { var text = @" interface Interface { int this[int w, int x, int y, string z] { get; set; } int this[int w, int x, string y, int z] { get; set; } int this[int w, int x, string y, string z] { get; set; } int this[int w, string x, int y, int z] { get; } int this[int w, string x, int y, string z] { get; } int this[int w, string x, string y, int z] { get; } int this[int w, string x, string y, string z] { set; } int this[string w, int x, int y, int z] { set; } int this[string w, int x, int y, string z] { set; } } class Class : Interface { int Interface.this[int w, int x, int y, string z] { get { return 1; } } int Interface.this[int w, int x, string y, int z] { set { } } int Interface.this[int w, int x, string y, string z] { get { return 1; } set { } } int Interface.this[int w, string x, int y, int z] { get { return 1; } } int Interface.this[int w, string x, int y, string z] { set { } } int Interface.this[int w, string x, string y, int z] { get { return 1; } set { } } int Interface.this[int w, string x, string y, string z] { get { return 1; } } int Interface.this[string w, int x, int y, int z] { set { } } int Interface.this[string w, int x, int y, string z] { get { return 1; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, int, int, string]' is missing accessor 'Interface.this[int, int, int, string].set' // int Interface.this[int w, int x, int y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, int, int, string]", "Interface.this[int, int, int, string].set").WithLocation(19, 19), // (20,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, int, string, int]' is missing accessor 'Interface.this[int, int, string, int].get' // int Interface.this[int w, int x, string y, int z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, int, string, int]", "Interface.this[int, int, string, int].get").WithLocation(20, 19), // (24,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, string, int, string]' is missing accessor 'Interface.this[int, string, int, string].get' // int Interface.this[int w, string x, int y, string z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, string, int, string]", "Interface.this[int, string, int, string].get").WithLocation(24, 19), // (24,60): error CS0550: 'Class.Interface.this[int, string, int, string].set' adds an accessor not found in interface member 'Interface.this[int, string, int, string]' // int Interface.this[int w, string x, int y, string z] { set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Class.Interface.this[int, string, int, string].set", "Interface.this[int, string, int, string]").WithLocation(24, 60), // (25,78): error CS0550: 'Class.Interface.this[int, string, string, int].set' adds an accessor not found in interface member 'Interface.this[int, string, string, int]' // int Interface.this[int w, string x, string y, int z] { get { return 1; } set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Class.Interface.this[int, string, string, int].set", "Interface.this[int, string, string, int]").WithLocation(25, 78), // (27,63): error CS0550: 'Class.Interface.this[int, string, string, string].get' adds an accessor not found in interface member 'Interface.this[int, string, string, string]' // int Interface.this[int w, string x, string y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Class.Interface.this[int, string, string, string].get", "Interface.this[int, string, string, string]").WithLocation(27, 63), // (27,19): error CS0551: Explicit interface implementation 'Class.Interface.this[int, string, string, string]' is missing accessor 'Interface.this[int, string, string, string].set' // int Interface.this[int w, string x, string y, string z] { get { return 1; } } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "this").WithArguments("Class.Interface.this[int, string, string, string]", "Interface.this[int, string, string, string].set").WithLocation(27, 19), // (29,60): error CS0550: 'Class.Interface.this[string, int, int, string].get' adds an accessor not found in interface member 'Interface.this[string, int, int, string]' // int Interface.this[string w, int x, int y, string z] { get { return 1; } set { } } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Class.Interface.this[string, int, int, string].get", "Interface.this[string, int, int, string]").WithLocation(29, 60), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, string, int].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, string, int].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, int, string].get' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, int, string].get").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, int, int, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, int, int, string].set").WithLocation(17, 15), // (17,15): error CS0535: 'Class' does not implement interface member 'Interface.this[int, string, string, string].set' // class Class : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class", "Interface.this[int, string, string, string].set").WithLocation(17, 15)); } [WorkItem(539162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539162")] [Fact] public void TestAbstractTypeMember() { var text = @" abstract partial class ConstantValue { abstract class ConstantValueDiscriminated : ConstantValue { } class ConstantValueBad : ConstantValue { } } "; //no errors CompileAndVerifyDiagnostics(text, new ErrorDescription[0]); } [Fact] public void OverridePrivatePropertyAccessor() { var text = @" public class Base { public virtual long Property1 { get; private set; } } public class Derived1 : Base { public override long Property1 { get; private set; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_OverrideNotExpected, "set").WithArguments("Derived1.Property1.set")); } [Fact] public void OverridePrivateIndexerAccessor() { var text = @" public class Base { public virtual long this[int x] { get { return 0; } private set { } } } public class Derived1 : Base { public override long this[int x] { get { return 0; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,66): error CS0115: 'Derived1.this[int].set': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "set").WithArguments("Derived1.this[int].set")); } [WorkItem(540221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540221")] [Fact] public void AbstractOverrideOnePropertyAccessor() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1").WithLocation(19, 9), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1").WithLocation(21, 18)); } [Fact] public void AbstractOverrideOneIndexerAccessor() { var text = @" public class Base1 { public virtual long this[long x] { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long this[long x] { get; } void test1() { this[0] += 1; } } public class Derived : Base2 { public override long this[long x] { get { return 1; } set { } } void test2() { base[0]++; base[0] = 2; long x = base[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.this[long]' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base[0]").WithArguments("Base2.this[long]").WithLocation(19, 9), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.this[long]' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base[0]").WithArguments("Base2.this[long]").WithLocation(21, 18)); } [Fact] public void TestHidingErrors() { // Tests: // Hide base virtual member using new // By default members should be hidden by signature if new is not specified // new should hide by signature var text = @" using System.Collections.Generic; class Base<T> { public virtual void Method() { } public virtual void Method(T x) { } public virtual void Method(T x, T y, List<T> a, Dictionary<T, T> b) { } public virtual void Method<U>(T x, T y) { } public virtual void Method<U>(U x, T y, List<U> a, Dictionary<T, U> b) { } public virtual int Property1 { get { return 0; } } public virtual int Property2 { get { return 0; } set { } } public virtual void Method2() { } public virtual void Method3() { } } class Derived<U> : Base<U> { public void Method(U x, U y) { } public new void Method(U x, U y, List<U> a, Dictionary<U, U> b) { } public new void Method<V>(V x, U y, List<V> a, Dictionary<U, V> b) { } public void Method<V>(V x, U y, List<V> a, Dictionary<V, U> b) { } public new virtual int Property1 { set { } } public new static int Property2 { get; set; } public new static void Method(U i) { } public new class Method2 { } public void Method<A, B>(U x, U y) { } public new int Method3 { get; set; } } class Derived2 : Derived<int> { public override void Method() { } public override void Method(int i) { } public override void Method(int x, int y, List<int> a, Dictionary<int, int> b) { } public override void Method<V>(V x, int y, List<V> a, Dictionary<int, V> b) { } public override void Method<U>(int x, int y) { } public override int Property1 { get { return 1; } } public override int Property2 { get; set; } public override void Method2() { } public override void Method3() { } } class Test { public static void Main() { Derived2 d2 = new Derived2(); Derived<int> d = d2; Base<int> b = d2; b.Method(); b.Method(1); b.Method<int>(1, 1); b.Method<int>(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method2(); int x = b.Property1; b.Property2 -= 1; b.Method3(); d.Method(); Derived<int>.Method(1); d.Method<int>(1, 1); d.Method<long>(1, 1, new List<long>(), new Dictionary<int, long>()); d.Method<long>(1, 1, new List<long>(), new Dictionary<long, int>()); d.Method(1, 1, new List<int>(), new Dictionary<int, int>()); d.Method2(); d.Method<int, int>(1, 1); Derived<int>.Method2 y = new Derived<int>.Method2(); // Both Method2's are visible? d.Property1 = 1; Derived<int>.Property2 = Derived<int>.Property2; d.Method3(); x = d.Method3; } }"; CreateCompilation(text).VerifyDiagnostics( // (31,26): error CS0506: 'Derived2.Method(int)': cannot override inherited member 'Derived<int>.Method(int)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method(int)", "Derived<int>.Method(int)"), // (32,26): error CS0506: 'Derived2.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)': cannot override inherited member 'Derived<int>.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)", "Derived<int>.Method(int, int, System.Collections.Generic.List<int>, System.Collections.Generic.Dictionary<int, int>)"), // (33,26): error CS0506: 'Derived2.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)': cannot override inherited member 'Derived<int>.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Method").WithArguments("Derived2.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)", "Derived<int>.Method<V>(V, int, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<int, V>)"), // (35,37): error CS0545: 'Derived2.Property1.get': cannot override because 'Derived<int>.Property1' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "get").WithArguments("Derived2.Property1.get", "Derived<int>.Property1"), // (36,25): error CS0506: 'Derived2.Property2': cannot override inherited member 'Derived<int>.Property2' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "Property2").WithArguments("Derived2.Property2", "Derived<int>.Property2"), // (37,26): error CS0505: 'Derived2.Method2()': cannot override because 'Derived<int>.Method2' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method2").WithArguments("Derived2.Method2()", "Derived<int>.Method2"), // (38,26): error CS0505: 'Derived2.Method3()': cannot override because 'Derived<int>.Method3' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method3").WithArguments("Derived2.Method3()", "Derived<int>.Method3")); } [Fact] public void TestOverloadingByRefOut() { var text = @" using System; abstract class Base { public abstract void Method(int x, ref int y, out Exception z); } abstract class Base2 : Base { public abstract void Method(int x, out int y, ref Exception z); // No warnings about hiding } class Derived2 : Base2 { public override void Method(int x, out int y, ref Exception z) { y = 0; } public override void Method(int x, ref int y, out Exception z) { z = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (14,26): error CS0663: 'Derived2' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public override void Method(int x, ref int y, out Exception z) { z = null; } Diagnostic(ErrorCode.ERR_OverloadRefKind, "Method").WithArguments("Derived2", "method", "ref", "out").WithLocation(14, 26)); } [Fact] public void TestOverloadingByParams() { var text = @" using System; abstract class Base { public abstract void Method(int x, params Exception[] z); public abstract void Method(int x, int[] z); } abstract class Base2 : Base { public abstract void Method(int x, Exception[] z); public abstract void Method(int x, params int[] z); }"; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0533: 'Base2.Method(int, System.Exception[])' hides inherited abstract member 'Base.Method(int, params System.Exception[])' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Method").WithArguments("Base2.Method(int, System.Exception[])", "Base.Method(int, params System.Exception[])"), // (10,26): warning CS0114: 'Base2.Method(int, System.Exception[])' hides inherited member 'Base.Method(int, params System.Exception[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Base2.Method(int, System.Exception[])", "Base.Method(int, params System.Exception[])"), // (11,26): error CS0533: 'Base2.Method(int, params int[])' hides inherited abstract member 'Base.Method(int, int[])' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Method").WithArguments("Base2.Method(int, params int[])", "Base.Method(int, int[])"), // (11,26): warning CS0114: 'Base2.Method(int, params int[])' hides inherited member 'Base.Method(int, int[])'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Base2.Method(int, params int[])", "Base.Method(int, int[])")); } [Fact] public void TestOverridingOmitLessAccessibleAccessor() { var text = @" using System.Collections.Generic; abstract class Base<T> { public abstract List<T> Property1 { get; internal set; } public abstract List<T> Property2 { set; internal get; } } abstract class Base2<T> : Base<T> { } class Derived : Base2<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; CreateCompilation(text).VerifyDiagnostics( // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property2.get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property2.get"), // (14,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property1.set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property1.set")); } [Fact] public void TestOverridingOmitInaccessibleAccessorInDifferentAssembly() { var text1 = @" using System; using System.Collections.Generic; public abstract class Base<T> { public abstract List<T> Property1 { get; internal set; } public abstract List<T> Property2 { set; internal get; } }"; var comp1 = CreateCompilation(text1); var text2 = @" using System.Collections.Generic; abstract class Base2<T> : Base<T> { } class Derived : Base2<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } }"; CreateCompilation(text2, new[] { new CSharpCompilationReference(comp1) }).VerifyDiagnostics( // (10,38): error CS0546: 'Derived.Property1': cannot override because 'Base<int>.Property1' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "Property1").WithArguments("Derived.Property1", "Base<int>.Property1"), // (11,38): error CS0545: 'Derived.Property2': cannot override because 'Base<int>.Property2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "Property2").WithArguments("Derived.Property2", "Base<int>.Property2"), // (8,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property1.set' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property1.set"), // (8,7): error CS0534: 'Derived' does not implement inherited abstract member 'Base<int>.Property2.get' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base<int>.Property2.get")); } [Fact] public void TestEmitSynthesizedSealedAccessorsInDifferentAssembly() { var source1 = @" using System; using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get; set; } public virtual List<T> Property2 { set { } get { return null; } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } } public sealed override List<int> Property2 { set { } } } class Derived2 : Derived { public override List<int> Property1 { set { } } public override List<int> Property2 { get { return null; } } }"; var comp = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); comp.VerifyDiagnostics( // (11,31): error CS0239: 'Derived2.Property1': cannot override inherited member 'Derived.Property1' because it is sealed Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Property1").WithArguments("Derived2.Property1", "Derived.Property1"), // (12,31): error CS0239: 'Derived2.Property2': cannot override inherited member 'Derived.Property2' because it is sealed Diagnostic(ErrorCode.ERR_CantOverrideSealed, "Property2").WithArguments("Derived2.Property2", "Derived.Property2")); } [Fact] public void TestOverrideAndHide() { // Tests: // Sanity check - within the same type declare members that respectively hide and override // a base virtual / abstract member var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual void Method<U>(T x) { } public abstract int Property { set; } } class Derived : Base<List<int>> { public override void Method<U>(List<int> x) { } public new void Method<U>(List<int> x) { } public override int Property { set { } } public new int Property { set{ } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,21): error CS0111: Type 'Derived' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Derived"), // (13,20): error CS0102: The type 'Derived' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Derived", "Property")); } [Fact] public void TestHidingByGenericArity() { // Tests: // Hide base virtual / abstract member with a nested type that has same name but different generic arity // Member should be available for overriding in further derived type var source = @" using System.Collections.Generic; class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { new class Method { } // Warning: new not required new class Property { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } } class NS2 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method { } public new class Property { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } // Error: can't override a type } } class NS3 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T> { } // Warning: new required public new class Property<T> { } // Warning: new not required } class Derived : Base2 { public override void Method<U>(List<int> x) { } // Error: can't override a type public override int Property { set { } } } } class NS4 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T, U> { } public class Property<T, U> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,19): warning CS0109: The member 'NS1.Base2.Method' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("NS1.Base2.Method"), // (35,30): error CS0505: 'NS2.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS2.Base2.Method' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS2.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS2.Base2.Method"), // (36,29): error CS0544: 'NS2.Derived.Property': cannot override because 'NS2.Base2.Property' is not a property Diagnostic(ErrorCode.ERR_CantOverrideNonProperty, "Property").WithArguments("NS2.Derived.Property", "NS2.Base2.Property"), // (48,22): warning CS0108: 'NS3.Base2.Method<T>' hides inherited member 'NS3.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("NS3.Base2.Method<T>", "NS3.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)"), // (49,26): warning CS0109: The member 'NS3.Base2.Property<T>' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("NS3.Base2.Property<T>"), // (53,30): error CS0505: 'NS3.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS3.Base2.Method<T>' is not a function Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS3.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS3.Base2.Method<T>")); } [WorkItem(540348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540348")] [Fact] public void TestOverridingBrokenTypes() { var text = @" using System.Collections.Generic; partial class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T> { } public new class Property<T> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } } partial class NS1 { abstract class Base<T> { public virtual void Method<U>(T x) { } public virtual int Property { set { } } } class Base2 : Base<List<int>> { public class Method<T, U> { } public class Property<T, U> { } } class Derived : Base2 { public override void Method<U>(List<int> x) { } public override int Property { set { } } } }"; // TODO: Dev10 reports fewer cascading errors CreateCompilation(text).VerifyDiagnostics( // (24,20): error CS0102: The type 'NS1' already contains a definition for 'Base' // abstract class Base<T> Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Base").WithArguments("NS1", "Base"), // (29,11): error CS0102: The type 'NS1' already contains a definition for 'Base2' // class Base2 : Base<List<int>> Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Base2").WithArguments("NS1", "Base2"), // (34,11): error CS0102: The type 'NS1' already contains a definition for 'Derived' // class Derived : Base2 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Derived").WithArguments("NS1", "Derived"), // (36,30): error CS0505: 'NS1.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS1.Base2.Method<T>' is not a function // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS1.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS1.Base2.Method<T>"), // (19,29): error CS0462: The inherited members 'NS1.Base<T>.Property' and 'NS1.Base<T>.Property' have the same signature in type 'NS1.Derived', so they cannot be overridden // public override int Property { set { } } Diagnostic(ErrorCode.ERR_AmbigOverride, "Property").WithArguments("NS1.Base<T>.Property", "NS1.Base<T>.Property", "NS1.Derived"), // (37,29): error CS0462: The inherited members 'NS1.Base<T>.Property' and 'NS1.Base<T>.Property' have the same signature in type 'NS1.Derived', so they cannot be overridden // public override int Property { set { } } Diagnostic(ErrorCode.ERR_AmbigOverride, "Property").WithArguments("NS1.Base<T>.Property", "NS1.Base<T>.Property", "NS1.Derived"), // (18,30): error CS0505: 'NS1.Derived.Method<U>(System.Collections.Generic.List<int>)': cannot override because 'NS1.Base2.Method<T>' is not a function // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Method").WithArguments("NS1.Derived.Method<U>(System.Collections.Generic.List<int>)", "NS1.Base2.Method<T>"), // (36,30): error CS0111: Type 'NS1.Derived' already defines a member called 'Method' with the same parameter types // public override void Method<U>(List<int> x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "NS1.Derived"), // (26,29): error CS0111: Type 'NS1.Base<T>' already defines a member called 'Method' with the same parameter types // public virtual void Method<U>(T x) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "NS1.Base<T>"), // (13,22): warning CS0108: 'NS1.Base2.Method<T>' hides inherited member 'NS1.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)'. Use the new keyword if hiding was intended. // public class Method<T> { } Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("NS1.Base2.Method<T>", "NS1.Base<System.Collections.Generic.List<int>>.Method<U>(System.Collections.Generic.List<int>)"), // (14,26): warning CS0109: The member 'NS1.Base2.Property<T>' does not hide an accessible member. The new keyword is not required. // public new class Property<T> { } Diagnostic(ErrorCode.WRN_NewNotRequired, "Property").WithArguments("NS1.Base2.Property<T>") ); } [Fact] public void TestHidingErrorsForVirtualMembers() { // Tests: // Hide non-existent base virtual member // Hide same virtual member more than once // Hide virtual member without specifying new // Overload virtual member and also specify new var text = @" class Base { internal new virtual void Method() { } internal virtual int Property { set { } } } partial class Derived : Base { public virtual void Method() { } public new virtual int Property { set { } } } partial class Derived { internal new virtual int Property { set { } } protected new virtual void Method<T>() { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,31): warning CS0109: The member 'Base.Method()' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Base.Method()"), // (14,30): error CS0102: The type 'Derived' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Derived", "Property"), // (9,25): warning CS0114: 'Derived.Method()' hides inherited member 'Base.Method()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Derived.Method()", "Base.Method()"), // (15,32): warning CS0109: The member 'Derived.Method<T>()' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived.Method<T>()")); } [Fact] public void TestHidingErrorLocations() { var text = @" class Base { public virtual void Method() { } public virtual int Property { set { } } protected class Type { } internal int Field = 1; } class Derived : Base { public new int MethOd = 2, Method = 3, METhod = 4; void Test() { long x = MethOd = Method = METhod; } class Base2 : Base { private long Type = 5, method = 2, Field = 2, field = 8, Property = 3; void Test() { long x = Type = method = Field = field = Property; } } }"; CreateCompilation(text).VerifyDiagnostics( // (12,20): warning CS0109: The member 'Derived.MethOd' does not hide an accessible member. The new keyword is not required. // public new int MethOd = 2, Method = 3, METhod = 4; Diagnostic(ErrorCode.WRN_NewNotRequired, "MethOd").WithArguments("Derived.MethOd"), // (12,44): warning CS0109: The member 'Derived.METhod' does not hide an accessible member. The new keyword is not required. // public new int MethOd = 2, Method = 3, METhod = 4; Diagnostic(ErrorCode.WRN_NewNotRequired, "METhod").WithArguments("Derived.METhod"), // (19,22): warning CS0108: 'Derived.Base2.Type' hides inherited member 'Base.Type'. Use the new keyword if hiding was intended. // private long Type = 5, method = 2, Field = 2, Diagnostic(ErrorCode.WRN_NewRequired, "Type").WithArguments("Derived.Base2.Type", "Base.Type"), // (19,44): warning CS0108: 'Derived.Base2.Field' hides inherited member 'Base.Field'. Use the new keyword if hiding was intended. // private long Type = 5, method = 2, Field = 2, Diagnostic(ErrorCode.WRN_NewRequired, "Field").WithArguments("Derived.Base2.Field", "Base.Field"), // (20,36): warning CS0108: 'Derived.Base2.Property' hides inherited member 'Base.Property'. Use the new keyword if hiding was intended. // field = 8, Property = 3; Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("Derived.Base2.Property", "Base.Property") ); } [Fact] public void ImplementInterfaceUsingSealedProperty() { var text = @" interface I1 { int Bar { get; } } class C1 { public virtual int Bar { get { return 0;} set { }} } class C2 : C1, I1 { sealed public override int Bar { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void ImplementInterfaceUsingSealedEvent() { var text = @" interface I1 { event System.Action E; } class C1 { public virtual event System.Action E; void UseEvent() { E(); } } class C2 : C1, I1 { public sealed override event System.Action E; void UseEvent() { E(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void ImplementInterfaceUsingNonVirtualEvent() { var text = @" interface I { event System.Action E; event System.Action F; event System.Action G; } class C : I { event System.Action I.E { add { } remove { } } public event System.Action F { add { } remove { } } public event System.Action G; } "; var compilation = CreateCompilation(text); // This also forces computation of IsMetadataVirtual. compilation.VerifyDiagnostics( // (12,32): warning CS0067: The event 'C.G' is never used // public event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); const int numEvents = 3; var @interface = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("I"); var interfaceEvents = new EventSymbol[numEvents]; interfaceEvents[0] = @interface.GetMember<EventSymbol>("E"); interfaceEvents[1] = @interface.GetMember<EventSymbol>("F"); interfaceEvents[2] = @interface.GetMember<EventSymbol>("G"); var @class = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classEvents = new EventSymbol[numEvents]; classEvents[0] = @class.GetEvent("I.E"); classEvents[1] = @class.GetMember<EventSymbol>("F"); classEvents[2] = @class.GetMember<EventSymbol>("G"); for (int i = 0; i < numEvents; i++) { var classEvent = classEvents[i]; var interfaceEvent = interfaceEvents[i]; Assert.Equal(classEvent, @class.FindImplementationForInterfaceMember(interfaceEvent)); Assert.Equal(classEvent.AddMethod, @class.FindImplementationForInterfaceMember(interfaceEvent.AddMethod)); Assert.Equal(classEvent.RemoveMethod, @class.FindImplementationForInterfaceMember(interfaceEvent.RemoveMethod)); Assert.True(classEvent.AddMethod.IsMetadataVirtual()); Assert.True(classEvent.RemoveMethod.IsMetadataVirtual()); } } [Fact] public void TestPrivateMemberHidesVirtualMember() { var text = @" abstract public class Class1 { public virtual void Member1() { } abstract class Class2 : Class1 { new private double[] Member1 = new double[] { }; abstract class Class3 : Class2 { public override void Member1() { base.Member1(); } // Error } } abstract class Class4 : Class2 { public override void Member1() { base.Member1(); } // OK } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_CantOverrideNonFunction, "Member1").WithArguments("Class1.Class2.Class3.Member1()", "Class1.Class2.Member1")); } [Fact] public void ImplicitMultipleInterfaceInGrandChild() { var text = @" interface I1 { void Bar(); } interface I2 { void Bar(); } class C1 : I1 { public void Bar() { } } class C2 : C1, I1, I2 { public new void Bar() { } } "; var comp = CreateCompilation(text); var c2Type = comp.Assembly.Modules[0].GlobalNamespace.GetTypeMembers("C2").Single(); comp.VerifyDiagnostics(DiagnosticDescription.None); Assert.True(c2Type.Interfaces().All(iface => iface.Name == "I1" || iface.Name == "I2")); } [WorkItem(540451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540451")] [Fact] public void TestImplicitImplSignatureMismatches() { // Tests: // Mismatching ref / out in signature of implemented member var source = @" using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Base { public void Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Toggle ref, out - CS0535 public void Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } } class Derived : Base, I2 // Implicit implementation in base { } class Class : I2 // Implicit implementation { public void Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Omit ref, out - CS0535 public void Method<U>(int a, U[] b, List<U>[] c) { b = null; } } class Class2 : I2 // Implicit implementation { // Additional ref - CS0535 public void Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } // Additional out - CS0535 public void Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (21,7): error CS0535: 'Derived' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Derived", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (24,7): error CS0535: 'Class' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (31,7): error CS0535: 'Class2' does not implement interface member 'I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])"), // (31,7): error CS0535: 'Class2' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])")); } [Fact] public void TestExplicitImplSignatureMismatches() { // Tests: // Mismatching ref / out in signature of implemented member var source = @" using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Class1 : I1<string>, I2 { void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Toggle ref, out - CS0535 void I2.Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } } class Class : I2 { void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } // Omit ref, out - CS0535 void I2.Method<U>(int a, U[] b, List<U>[] c) { b = null; } } class Class2 : I2, I1<string> { // Additional ref - CS0535 void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } // Additional out - CS0535 void I2.Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS0539: 'Class.Method<U>(int, U[], System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(int a, U[] b, List<U>[] c) { b = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class.Method<U>(int, U[], System.Collections.Generic.List<U>[])"), // (17,13): error CS0539: 'Class1.Method<U>(ref int, out U[], System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(ref int a, out U[] b, List<U>[] c) { b = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class1.Method<U>(ref int, out U[], System.Collections.Generic.List<U>[])"), // (20,15): error CS0535: 'Class' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (13,28): error CS0535: 'Class1' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class1 : I1<string>, I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class1", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (22,40): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (15,40): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (22,54): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (15,54): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(int a, long b = 2, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (32,13): error CS0539: 'Class2.Method<U>(ref int, out U[], out System.Collections.Generic.List<U>[])' in explicit interface declaration is not a member of interface // void I2.Method<U>(ref int a, out U[] b, out List<U>[] c) { b = null; c = null; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method<U>(ref int, out U[], out System.Collections.Generic.List<U>[])"), // (30,21): error CS0539: 'Class2.Method(ref int, long, string, params System.Collections.Generic.List<string>[])' in explicit interface declaration is not a member of interface // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method(ref int, long, string, params System.Collections.Generic.List<string>[])"), // (27,16): error CS0535: 'Class2' does not implement interface member 'I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])' // class Class2 : I2, I1<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("Class2", "I2.Method<T>(out int, ref T[], System.Collections.Generic.List<T>[])"), // (27,20): error CS0535: 'Class2' does not implement interface member 'I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])' // class Class2 : I2, I1<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<string>").WithArguments("Class2", "I1<string>.Method(int, long, string, params System.Collections.Generic.List<string>[])"), // (30,44): warning CS1066: The default value specified for parameter 'b' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "b").WithArguments("b"), // (30,58): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1<string>.Method(ref int a, long b = 3, string c = null, params List<string>[] d) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c")); } [Fact] public void TestImplicitImplSignatureMismatches2() { // Tests: // Change return type of implemented member // Change parameter types of implemented member // Change number / order of generic method type parameters in implemented method //UNDONE: type constraint mismatch var text = @" interface Interface { void Method<T>(long l, int i); } interface Interface2 { void Method<T, U, V>(T l, U i, V z); } interface Interface3 { int Property {set;} } class Class1 : Interface { public void Method<T, U>(long l, int i) { } //wrong arity } class Base2 { public void Method(long l, int i) { } //wrong arity } class Class2 : Base2, Interface { } class Base3 { public void Method<V, T, U>(T l, U i, V z) { } //wrong order } class Base31 : Base3 { } class Class3 : Base31, Interface2 { } class Class4 : Interface { public int Method<T>(long l, int i) { return 0; } //wrong return type } class Class41 : Interface3 { public long Property { set { } } //wrong return type } class Class5 : Interface { public void Method1<T>(long l, int i) { } //wrong name } class Class6 : Interface { public void Method<T>(long l) { } //wrong parameter count } class Base7 { public void Method<T>(int i, long l) { } //wrong parameter types } class Class7 : Base7, Interface { } "; CreateCompilation(text).VerifyDiagnostics( // (17,16): error CS0535: 'Class1' does not implement interface member 'Interface.Method<T>(long, int)' // class Class1 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class1", "Interface.Method<T>(long, int)").WithLocation(17, 16), // (26,23): error CS0535: 'Class2' does not implement interface member 'Interface.Method<T>(long, int)' // class Class2 : Base2, Interface { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class2", "Interface.Method<T>(long, int)").WithLocation(26, 23), // (33,24): error CS0535: 'Class3' does not implement interface member 'Interface2.Method<T, U, V>(T, U, V)' // class Class3 : Base31, Interface2 { } Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class3", "Interface2.Method<T, U, V>(T, U, V)").WithLocation(33, 24), // (58,23): error CS0535: 'Class7' does not implement interface member 'Interface.Method<T>(long, int)' // class Class7 : Base7, Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class7", "Interface.Method<T>(long, int)").WithLocation(58, 23), // (49,16): error CS0535: 'Class6' does not implement interface member 'Interface.Method<T>(long, int)' // class Class6 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class6", "Interface.Method<T>(long, int)").WithLocation(49, 16), // (35,16): error CS0738: 'Class4' does not implement interface member 'Interface.Method<T>(long, int)'. 'Class4.Method<T>(long, int)' cannot implement 'Interface.Method<T>(long, int)' because it does not have the matching return type of 'void'. // class Class4 : Interface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface").WithArguments("Class4", "Interface.Method<T>(long, int)", "Class4.Method<T>(long, int)", "void").WithLocation(35, 16), // (39,17): error CS0738: 'Class41' does not implement interface member 'Interface3.Property'. 'Class41.Property' cannot implement 'Interface3.Property' because it does not have the matching return type of 'int'. // class Class41 : Interface3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Interface3").WithArguments("Class41", "Interface3.Property", "Class41.Property", "int").WithLocation(39, 17), // (44,16): error CS0535: 'Class5' does not implement interface member 'Interface.Method<T>(long, int)' // class Class5 : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class5", "Interface.Method<T>(long, int)").WithLocation(44, 16)); } [WorkItem(540470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540470")] [Fact] public void TestExplicitImplSignatureMismatches2() { // Tests: // Change return type of implemented member // Change parameter types of implemented member // Change number / order of generic method type parameters in implemented method //UNDONE: type constraint mismatch var text = @" interface Interface { void Method<T>(long l, int i); } interface Interface2 { void Method<T, U, V>(T l, U i, V z); } interface Interface3 { int Property {set;} } class Class1 : Interface { void Interface.Method<T, U>(long l, int i) { } //wrong arity } class Class2 : Interface { void Interface.Method(long l, int i) { } //wrong arity } class Class3 : Interface2 { void Interface2.Method<V, T, U>(T l, U i, V z) { } //wrong order } class Class4 : Interface { int Interface.Method<T>(long l, int i) { return 0; } //wrong return type } class Class41 : Interface3 { long Interface3.Property { set { } } //wrong return type } class Class5 : Interface { void Interface.Method1<T>(long l, int i) { } //wrong name } class Class51 : Interface { void INterface.Method<T>(long l, int i) { } //wrong name } class Class52 : Interface, Interface2 { void Interface.Method<T, U, V>(T l, U i, V z) { } //wrong name } class Class6 : Interface { void Interface.Method<T>(long l) { } //wrong parameter count } class Class7 : Interface { void Interface.Method<T>(int i, long l) { } //wrong parameter types } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "INterface").WithArguments("INterface"), Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "INterface").WithArguments("INterface"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class1.Method<T, U>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class4.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class51", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class1", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class4", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Class41.Property"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class2.Method(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class2", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface3").WithArguments("Class41", "Interface3.Property"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class52.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class52", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class52", "Interface2.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class7.Method<T>(int, long)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class7", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method1").WithArguments("Class5.Method1<T>(long, int)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class3.Method<V, T, U>(T, U, V)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class5", "Interface.Method<T>(long, int)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface2").WithArguments("Class3", "Interface2.Method<T, U, V>(T, U, V)"), Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Class6.Method<T>(long)"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Class6", "Interface.Method<T>(long, int)")); } [Fact] public void TestDuplicateImplicitImpl() { // Tests: // Implement same interface member more than once in different parts of a partial type var text = @" using System.Collections.Generic; interface I1 { int Property { set; } } abstract partial class Class : I2, I1 { abstract public int Property { set; } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } interface I2 : I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I3 { abstract public int Property { get; set; } abstract public void Method<T>(int a, ref T[] b, out List<T> c); abstract public void Method(int a = 3, params System.Exception[] b); } abstract partial class Base { abstract public int Property { set; } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } interface I3 : I2 { void Method(int a = 3, params System.Exception[] b); } abstract partial class Base { abstract public int Property { get; set; } abstract public void Method<T>(int a, ref T[] b, out List<T> c); abstract public void Method(int a = 3, params System.Exception[] b); } abstract class Derived : Base, I3, I1 { }"; CreateCompilation(text).VerifyDiagnostics( // (18,25): error CS0102: The type 'Class' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Class", "Property"), // (19,26): error CS0111: Type 'Class' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Class"), // (33,25): error CS0102: The type 'Base' already contains a definition for 'Property' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Base", "Property"), // (34,26): error CS0111: Type 'Base' already defines a member called 'Method' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("Method", "Base")); } [Fact] public void TestDuplicateExplicitImpl() { // Tests: // Implement same interface member more than once in different parts of a partial type var text = @" using System.Collections.Generic; using Type = System.Int32; interface I1 { int Property { set; } } abstract partial class Class : I2, I1 { int I1.Property { set { } } void I2.Method<U>(int a, ref U[] b, out List<U> c) { c = null; } } interface I3 : I2 { void Method(int a = 3, params System.Exception[] b); } interface I2 : I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I3 { Type I1.Property { set { } } void I2.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } void I3.Method(int a = 3, params System.Exception[] b) { } }"; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS8646: 'I2.Method<T>(int, ref T[], out List<T>)' is explicitly implemented more than once. // abstract partial class Class : I2, I1 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "Class").WithArguments("I2.Method<T>(int, ref T[], out System.Collections.Generic.List<T>)").WithLocation(8, 24), // (8,24): error CS8646: 'I1.Property' is explicitly implemented more than once. // abstract partial class Class : I2, I1 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "Class").WithArguments("I1.Property").WithLocation(8, 24), // (25,24): warning CS1066: The default value specified for parameter 'a' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I3.Method(int a = 3, params System.Exception[] b) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "a").WithArguments("a"), // (23,13): error CS0102: The type 'Class' already contains a definition for 'I1.Property' // Type I1.Property { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Property").WithArguments("Class", "I1.Property"), // (24,13): error CS0111: Type 'Class' already defines a member called 'I2.Method' with the same parameter types // void I2.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Method").WithArguments("I2.Method", "Class")); } [Fact] public void TestMissingImpl() { // Tests: // For partial interfaces – test that compiler generates error if any interface methods have not been implemented // Test that compiler generates error if any interface methods have not been implemented in an abstract class var text = @" using System.Collections.Generic; partial interface I1 { int Property { set; } } abstract partial class Class : I1 { int I1.Property { set { } } abstract public void Method<U>(int a, ref U[] b, out List<U> c); } partial interface I1 { void Method<T>(int a, ref T[] b, out List<T> c); } abstract partial class Class : I1 { void Method(int a = 3, params System.ArgumentException[] b) { } // incorrect parameter type } abstract class Base { abstract public void Method(int a = 3, params System.Exception[] b); long Property { set { } } // incorrect return type } abstract class Base2 : Base { } partial interface I1 { void Method(int a = 3, params System.Exception[] b); } abstract class Derived : Base2, I1 { void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,32): error CS0535: 'Class' does not implement interface member 'I1.Method(int, params System.Exception[])' // abstract partial class Class : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("Class", "I1.Method(int, params System.Exception[])").WithLocation(7, 32), // (32,33): error CS0737: 'Derived' does not implement interface member 'I1.Property'. 'Base.Property' cannot implement an interface member because it is not public. // abstract class Derived : Base2, I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("Derived", "I1.Property", "Base.Property").WithLocation(32, 33)); } [Fact] public void TestInterfaceBaseAccessError() { // Tests: // Invoke base.InterfaceMember from within class that only inherits an interface var text = @" using System.Collections.Generic; partial interface I1 { int Property { set; } void Method<T>(int a, ref T[] b, out List<T> c); void Method(int a = 3, params System.Exception[] b); } class Class1 : I1 { public int Property { set { base.Property = value; } } public void Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } public void Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } } class Class2 : I1 { int I1.Property { set { base.Property = value; } } void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } }"; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS1066: The default value specified for parameter 'a' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "a").WithArguments("a"), // (11,38): error CS0117: 'object' does not contain a definition for 'Property' // public int Property { set { base.Property = value; } } Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property"), // (12,77): error CS0117: 'object' does not contain a definition for 'Method' // public void Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method<T>").WithArguments("object", "Method"), // (13,71): error CS0117: 'object' does not contain a definition for 'Method' // public void Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method"), // (17,34): error CS0117: 'object' does not contain a definition for 'Property' // int I1.Property { set { base.Property = value; } } Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("object", "Property"), // (18,73): error CS0117: 'object' does not contain a definition for 'Method' // void I1.Method<T>(int a, ref T[] b, out List<T> c) { c = null; base.Method<T>(a, b, c); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method<T>").WithArguments("object", "Method"), // (19,67): error CS0117: 'object' does not contain a definition for 'Method' // void I1.Method(int a = 3, params System.Exception[] b) { base.Method(a, b); } Diagnostic(ErrorCode.ERR_NoSuchMember, "Method").WithArguments("object", "Method")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Implicit() { // Tests: // In signature / name of implicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<K>(T a, U[] b, List<V> c, Interface<W, K> d); } internal class Base<X, Y> { public Y Property { set { } } public void Method<V>(X A, int[] b, List<long> C, Outer<Y>.Inner<int>.Interface<Y, V> d) { } } } } internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> { public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> { public List<List<uint>> Property { get { return null; } set { } } public void Method<K>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<long>>>.Inner<List<List<T>>>.Interface<List<int>, K> D) { } public void Method<T>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<List<int>, T> D) { } } } public class Test { public static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (25,63): error CS0535: 'Derived1<U, T>' does not implement interface member 'Outer<U>.Inner<int>.Interface<long, T>.Method<K>(U, int[], System.Collections.Generic.List<long>, Outer<U>.Inner<int>.Interface<T, K>)' // internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<int>.Interface<long, T>").WithArguments("Derived1<U, T>", "Outer<U>.Inner<int>.Interface<long, T>.Method<K>(U, int[], System.Collections.Generic.List<long>, Outer<U>.Inner<int>.Interface<T, K>)").WithLocation(25, 63), // (25,63): error CS0738: 'Derived1<U, T>' does not implement interface member 'Outer<U>.Inner<int>.Interface<long, T>.Property'. 'Outer<U>.Inner<T>.Base<U, T>.Property' cannot implement 'Outer<U>.Inner<int>.Interface<long, T>.Property' because it does not have the matching return type of 'U'. // internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Outer<U>.Inner<int>.Interface<long, T>").WithArguments("Derived1<U, T>", "Outer<U>.Inner<int>.Interface<long, T>.Property", "Outer<U>.Inner<T>.Base<U, T>.Property", "U").WithLocation(25, 63), // (27,27): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'Derived1<U, T>' // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "Derived1<U, T>").WithLocation(27, 27), // (37,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'Derived1<U, T>' // public void Method<T>(List<List<int>> A, List<List<T>>[] B, List<long> C, Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<List<int>, T> D) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "Derived1<U, T>").WithLocation(37, 28), // (27,32): error CS0535: 'Derived1<U, T>.Derived2<T>' does not implement interface member 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Method<K>(System.Collections.Generic.List<System.Collections.Generic.List<int>>, System.Collections.Generic.List<System.Collections.Generic.List<T>>[], System.Collections.Generic.List<long>, Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<System.Collections.Generic.List<int>, K>)' // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>>").WithArguments("Derived1<U, T>.Derived2<T>", "Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Method<K>(System.Collections.Generic.List<System.Collections.Generic.List<int>>, System.Collections.Generic.List<System.Collections.Generic.List<T>>[], System.Collections.Generic.List<long>, Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<System.Collections.Generic.List<int>, K>)").WithLocation(27, 32), // (27,32): error CS0738: 'Derived1<U, T>.Derived2<T>' does not implement interface member 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property'. 'Derived1<U, T>.Derived2<T>.Property' cannot implement 'Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property' because it does not have the matching return type of 'System.Collections.Generic.List<System.Collections.Generic.List<int>>'. // public class Derived2<T> : Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "Outer<List<List<int>>>.Inner<List<List<T>>>.Interface<long, List<int>>").WithArguments("Derived1<U, T>.Derived2<T>", "Outer<System.Collections.Generic.List<System.Collections.Generic.List<int>>>.Inner<System.Collections.Generic.List<System.Collections.Generic.List<T>>>.Interface<long, System.Collections.Generic.List<int>>.Property", "Derived1<U, T>.Derived2<T>.Property", "System.Collections.Generic.List<System.Collections.Generic.List<int>>").WithLocation(27, 32)); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived1 : Inner<int>.Interface<ulong, string> { T Outer<T>.Inner<int>.Interface<long, string>.Property { set { } } void Inner<int>.Interface<long, string>.Method<K>(T A, int[] B, List<long> c, Dictionary<string, K> D) { } internal class Derived2<X, Y> : Outer<Y>.Inner<int>.Interface<long, X> { X Outer<X>.Inner<int>.Interface<long, Y>.Property { set { } } void Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X A, int[] b, List<long> C, Dictionary<Y, K> d) { } } } internal class Derived3 : Interface<long, string> { U Inner<U>.Interface<long, string>.Property { set { } } void Outer<T>.Inner<U>.Interface<long, string>.Method<K>(T a, K[] B, List<long> C, Dictionary<string, K> d) { } } internal class Derived4 : Outer<U>.Inner<T>.Interface<T, U> { U Outer<U>.Inner<T>.Interface<T, U>.Property { set { } } void Outer<U>.Inner<T>.Interface<T, U>.Method<K>(U a, T[] b, List<U> C, Dictionary<U, K> d) { } internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) { } internal class Derived6<u> : Outer<List<T>>.Inner<U>.Interface<List<u>, T> { List<T> Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Property { set { } } void Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Method<K>(List<T> AA, U[] b, List<List<U>> c, Dictionary<T, K> d) { } } internal class Derived7<u> : Outer<List<T>>.Inner<U>.Interface<List<U>, T> { List<u> Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Property { set { } } void Outer<List<T>>.Inner<U>.Interface<List<U>, T>.Method<K>(List<T> AA, U[] b, List<List<u>> c, Dictionary<T, K> d) { } } } } } } class Test { public static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (48,52): error CS0539: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, K>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)"), // (57,47): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)"), // (51,39): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5' does not implement interface member 'Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<T>.Inner<U>.Interface<U, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5", "Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)"), // (72,75): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Property"), // (76,72): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, K>)"), // (70,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, Z>)"), // (70,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived7<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property"), // (62,29): error CS0540: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property': containing type does not implement interface 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Property", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>"), // (66,26): error CS0540: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, K>)': containing type does not implement interface 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<List<T>>.Inner<U>.Interface<List<U>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>.Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>.Method<K>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<U>>, System.Collections.Generic.Dictionary<T, K>)", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<U>, T>"), // (60,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<u>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Method<Z>(System.Collections.Generic.List<T>, U[], System.Collections.Generic.List<System.Collections.Generic.List<u>>, System.Collections.Generic.Dictionary<T, Z>)"), // (60,46): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>' does not implement interface member 'Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<List<T>>.Inner<U>.Interface<List<u>, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Derived6<u>", "Outer<System.Collections.Generic.List<T>>.Inner<U>.Interface<System.Collections.Generic.List<u>, T>.Property"), // (14,15): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Property': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<T>.Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Property", "Outer<T>.Inner<int>.Interface<long, string>"), // (18,18): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Method<K>(T, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<int>.Interface<long, string>.Method<K>(T, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)", "Outer<T>.Inner<int>.Interface<long, string>"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<ulong, string>.Method<Z>(T, int[], System.Collections.Generic.List<ulong>, System.Collections.Generic.Dictionary<string, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<ulong, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<ulong, string>.Method<Z>(T, int[], System.Collections.Generic.List<ulong>, System.Collections.Generic.Dictionary<string, Z>)"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<ulong, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<ulong, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<ulong, string>.Property"), // (23,19): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Property': containing type does not implement interface 'Outer<X>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Property", "Outer<X>.Inner<int>.Interface<long, Y>"), // (27,22): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)': containing type does not implement interface 'Outer<X>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Outer<X>.Inner<int>.Interface<long, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)", "Outer<X>.Inner<int>.Interface<long, Y>"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<Y>.Inner<int>.Interface<long, X>.Method<Z>(Y, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<X, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<Y>.Inner<int>.Interface<long, X>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<Y>.Inner<int>.Interface<long, X>.Method<Z>(Y, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<X, Z>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<Y>.Inner<int>.Interface<long, X>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<Y>.Inner<int>.Interface<long, X>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<Y>.Inner<int>.Interface<long, X>.Property"), // (34,48): error CS0539: 'Outer<T>.Inner<U>.Derived3.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived3.Property"), // (38,60): error CS0539: 'Outer<T>.Inner<U>.Derived3.Method<K>(T, K[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived3.Method<K>(T, K[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, K>)"), // (32,35): error CS0535: 'Outer<T>.Inner<U>.Derived3' does not implement interface member 'Outer<T>.Inner<U>.Interface<long, string>.Method<Z>(T, U[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived3", "Outer<T>.Inner<U>.Interface<long, string>.Method<Z>(T, U[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<string, Z>)"), // (32,35): error CS0535: 'Outer<T>.Inner<U>.Derived3' does not implement interface member 'Outer<T>.Inner<U>.Interface<long, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived3", "Outer<T>.Inner<U>.Interface<long, string>.Property")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_HideTypeParameter() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,67): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (10,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' // void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (10,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' // void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (17,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)' in explicit interface declaration is not a member of interface // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (14,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' in explicit interface declaration is not a member of interface // void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' // internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' // internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Implicit_HideTypeParameter() { // Tests: // In signature / name of explicitly implemented member, use generic type whose open type (C<T>) matches signature // in base interface - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { void Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } void Outer<X>.Inner<int>.Interface<long, Y>.Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,64): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,67): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (10,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (10,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (17,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (14,57): error CS0539: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)"), // (12,41): error CS0535: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)")); } [Fact] public void TestErrorsOverridingGenericNestedClasses_HideTypeParameter() { // Tests: // In signature / name of overridden member, use generic type whose open type (C<T>) matches signature // in base class - but the closed type (C<string> / C<U>) does not match var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal abstract class Base<V, W> { internal virtual void Method<X>(T a, U[] b, List<V> c, Dictionary<W, X> d) { } internal abstract void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<X>.Inner<int>.Base<long, Y> { internal override void Method<X>(X A, int[] b, List<long> C, Dictionary<Y, X> d) { } internal override void Method<X, Y>(X A, int[] b, List<X> C, Dictionary<Y, Y> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (10,43): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Base<V, W>"), // (10,46): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Base<V, W>"), // (14,43): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,43): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (17,46): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (14,36): error CS0115: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, X>)"), // (17,36): error CS0115: 'Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Method").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>.Method<X, Y>(X, int[], System.Collections.Generic.List<X>, System.Collections.Generic.Dictionary<Y, Y>)"), // (12,24): error CS0534: 'Outer<T>.Inner<U>.Derived1<X, Y>' does not implement inherited abstract member 'Outer<X>.Inner<int>.Base<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)' Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived1").WithArguments("Outer<T>.Inner<U>.Derived1<X, Y>", "Outer<X>.Inner<int>.Base<long, Y>.Method<V, W>(X, int[], System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<W, W>)")); } [Fact] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_IncorrectPartialQualification() { // Tests: // In name of explicitly implemented member specify incorrect partially qualified type name var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived1 : Inner<int>.Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<int>.Interface<long, string>.Method<K>(T A, int[] B, List<long> c, Dictionary<string, K> D) { } internal class Derived2<X, Y> : Outer<X>.Inner<int>.Interface<long, Y> { X Inner<int>.Interface<long, Y>.Property { set { } } void Inner<long>.Interface<long, Y>.Method<K>(X A, int[] b, List<long> C, Dictionary<Y, K> d) { } } } internal class Derived3 : Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<U>.Interface<long, string>.Method<K>(T a, U[] B, List<long> C, Dictionary<string, K> d) { } } internal class Derived4 : Outer<U>.Inner<T>.Interface<T, U> { U Interface<T, U>.Property { set { } } void Inner<T>.Interface<T, U>.Method<K>(U a, T[] b, List<T> C, Dictionary<U, K> d) { } } } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (44,15): error CS0540: 'Outer<T>.Inner<U>.Derived4.Property': containing type does not implement interface 'Outer<T>.Inner<U>.Interface<T, U>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4.Property", "Outer<T>.Inner<U>.Interface<T, U>"), // (44,31): error CS0539: 'Outer<T>.Inner<U>.Derived4.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived4.Property"), // (48,18): error CS0540: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)': containing type does not implement interface 'Outer<T>.Inner<T>.Interface<T, U>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)", "Outer<T>.Inner<T>.Interface<T, U>"), // (48,43): error CS0539: 'Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Method<K>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, K>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Method<Z>(U, T[], System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<U, Z>)"), // (42,35): error CS0535: 'Outer<T>.Inner<U>.Derived4' does not implement interface member 'Outer<U>.Inner<T>.Interface<T, U>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<U>.Inner<T>.Interface<T, U>").WithArguments("Outer<T>.Inner<U>.Derived4", "Outer<U>.Inner<T>.Interface<T, U>.Property"), // (14,15): error CS0540: 'Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<U>.Interface<long, string>.Property': containing type does not implement interface 'Outer<T>.Inner<U>.Interface<long, string>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1.Outer<T>.Inner<U>.Interface<long, string>.Property", "Outer<T>.Inner<U>.Interface<long, string>"), // (12,35): error CS0535: 'Outer<T>.Inner<U>.Derived1' does not implement interface member 'Outer<T>.Inner<int>.Interface<long, string>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Inner<int>.Interface<long, string>").WithArguments("Outer<T>.Inner<U>.Derived1", "Outer<T>.Inner<int>.Interface<long, string>.Property"), // (23,19): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property': containing type does not implement interface 'Outer<T>.Inner<int>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property", "Outer<T>.Inner<int>.Interface<long, Y>"), // (23,49): error CS0539: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Property").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Property"), // (27,22): error CS0540: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)': containing type does not implement interface 'Outer<T>.Inner<long>.Interface<long, Y>' Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner<long>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)", "Outer<T>.Inner<long>.Interface<long, Y>"), // (27,53): error CS0539: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)' in explicit interface declaration is not a member of interface Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>.Method<K>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, K>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Method<Z>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, Z>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Method<Z>(X, int[], System.Collections.Generic.List<long>, System.Collections.Generic.Dictionary<Y, Z>)"), // (21,45): error CS0535: 'Outer<T>.Inner<U>.Derived1.Derived2<X, Y>' does not implement interface member 'Outer<X>.Inner<int>.Interface<long, Y>.Property' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<X>.Inner<int>.Interface<long, Y>").WithArguments("Outer<T>.Inner<U>.Derived1.Derived2<X, Y>", "Outer<X>.Inner<int>.Interface<long, Y>.Property")); } [Fact] public void TestImplicitImplementationSubstitutionError() { // Tests: // Implicitly implement interface member in base generic type – the method that implements interface member // should depend on type parameter of base type to satisfy signature (return type / parameter type) equality // Test case where substitution is incorrect var source = @" using System.Collections.Generic; interface Interface { void Method(List<int> x); void Method(List<long> z); } class Base<T> { public void Method(T x) { } } class Base2<T> : Base<T> { public void Method(List<long> x) { } } class Derived : Base2<List<uint>>, Interface { } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (16,7): error CS0535: 'Derived' does not implement interface member 'Interface.Method(System.Collections.Generic.List<int>)' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Derived", "Interface.Method(System.Collections.Generic.List<int>)")); } [Fact] public void TestImplementAmbiguousSignaturesImplicitly_Errors() { // Tests: // Use a single member to implicitly implement // multiple base interface members that have signatures differing only by params // Implicitly implement multiple base interface members that // have signatures differing only by ref/out (some of these will be error cases) var text = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Test : I3 { public int P { get { return 0; } set { Console.WriteLine(""I1.P""); } } // public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } - Not possible to implement I3.P implicitly // public void M1(long x) { Console.WriteLine(""I1.M1""); } - Not possible to implement I1.M1 implicitly public int M1(long x) { Console.WriteLine(""I3.M1""); return 0; } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } // public void M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } - Not possible to implement I1.M6 implicitly public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } public void M7(ref long x) { Console.WriteLine(""I3.M7""); } // public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } - Not possible to implement I1.M7 implicitly public void M8(long[] x) { Console.WriteLine(""I3.M8+I1.M9""); } // Implements both I3.M8 and I1.M8 public void M9(params long[] x) { Console.WriteLine(""I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 }"; CreateCompilation(text).VerifyDiagnostics( // (32,14): error CS0738: 'Test' does not implement interface member 'I3.P'. 'Test.P' cannot implement 'I3.P' because it does not have the matching return type of 'long'. // class Test : I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I3").WithArguments("Test", "I3.P", "Test.P", "long").WithLocation(32, 14), // (32,14): error CS0738: 'Test' does not implement interface member 'I1.M1(long)'. 'Test.M1(long)' cannot implement 'I1.M1(long)' because it does not have the matching return type of 'void'. // class Test : I3 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I3").WithArguments("Test", "I1.M1(long)", "Test.M1(long)", "void").WithLocation(32, 14), // (32,14): error CS0535: 'Test' does not implement interface member 'I1.M6(ref long)' // class Test : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test", "I1.M6(ref long)").WithLocation(32, 14), // (32,14): error CS0535: 'Test' does not implement interface member 'I1.M7(out long)' // class Test : I3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I3").WithArguments("Test", "I1.M7(out long)").WithLocation(32, 14)); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors() { // Tests: // Implicitly / explicitly implement multiple base interface members (that have same signature) with a single member // Implicitly / explicitly implement multiple base interface members (that have same signature) with a single member from base class var source = @" using System; interface I1<T, U> { void Method<V>(T x, Func<U, T, V> v, U z); void Method<Z>(U x, Func<T, U, Z> v, T z); } class Implicit : I1<int, Int32> { public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Base { public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Base2 : Base { } class ImplicitInBase : Base2, I1<int, Int32> { } class Explicit : I1<int, Int32> { void I1<Int32, Int32>.Method<V>(int x, Func<int, int, V> v, int z) { } public void Method<V>(int x, Func<int, int, V> v, int z) { } } class Test { public static void Main() { I1<int, int> i = new Implicit(); Func<int, int, string> x = null; i.Method<string>(1, x, 1); i = new ImplicitInBase(); i.Method<string>(1, x, 1); i = new Explicit(); i.Method<string>(1, x, 1); } }"; CreateCompilation(source).VerifyDiagnostics( // (20,27): warning CS0473: Explicit interface implementation 'Explicit.I1<int, int>.Method<V>(int, System.Func<int, int, V>, int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void I1<Int32, Int32>.Method<V>(int x, Func<int, int, V> v, int z) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Explicit.I1<int, int>.Method<V>(int, System.Func<int, int, V>, int)"), // (29,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)"), // (32,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)"), // (35,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)' and 'I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)' // i.Method<string>(1, x, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "Method<string>").WithArguments("I1<T, U>.Method<V>(T, System.Func<U, T, V>, U)", "I1<T, U>.Method<Z>(U, System.Func<T, U, Z>, T)")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors2() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, U v, U[] y); int Method(U x, T v, params U[] y); // Add params and change return type } class Implicit : I1<int, int> { public Action<int> Method(ref int x) { Console.WriteLine(""Method(ref int x)""); return null; } public Action<int> Method(int x) { Console.WriteLine(""Method(int x)""); return null; } public void Method(ref Func<int, int> v) { Console.WriteLine(""Method(ref Func<int, int> v)""); } // We have to implement this explicitly void I1<int, int>.Method(out Func<int, int> v) { v = null; Console.WriteLine(""I1<int, int>.Method(out Func<int, int> v)""); } public void Method(int x, int[] y) { Console.WriteLine(""Method(int x, int[] y)""); } // Implements both params and non-params version public long Method(int x, int v, int[] y) { Console.WriteLine(""Method(int x, int v, int[] y)""); return 0; } // We have to implement this explicitly int I1<int, int>.Method(int x, int v, params int[] y) { Console.WriteLine(""I1<int, int>.Method(int x, int v, params int[] y)""); return 0; } } class Test { public static void Main() { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(out System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(out System.Func<int, int>)")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors3() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, Func<T, U> v, U[] y); int Method(U x, Func<T, U> v, params U[] y); // Add params and change return type } class Base { public Action<int> Method(ref int x) { Console.WriteLine(""Method(ref int x)""); return null; } public Action<int> Method(int x) { Console.WriteLine(""Method(int x)""); return null; } public void Method(ref Func<int, int> v) { Console.WriteLine(""Method(ref Func<int, int> v)""); } public void Method(int x, int[] y) { Console.WriteLine(""Method(int x, int[] y)""); } public long Method(int x, Func<int, int> v, int[] y) { Console.WriteLine(""long Method(int x, Func<int, int> v, int[] y)""); return 0; } } class ImplicitInBase : Base, I1<int, int> { public void Method(out Func<int, int> v) { v = null; Console.WriteLine(""Method(out Func<int, int> v)""); } public int Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine(""int Method(int x, Func<int, int> v, params int[] y)""); return 0; } } class Test { public static void Main() { I1<int, int> i = new ImplicitInBase(); int x = 1; Func<int, int> y = null; i.Method(ref x); i.Method(x); i.Method(ref y); i.Method(out y); i.Method(x, new int[] { x, x, x }); i.Method(x, x, x, x); i.Method(x, y, new int[] { x, x, x }); i.Method(x, y, x, x, x); } }"; CreateCompilation(source).VerifyDiagnostics( // (25,16): warning CS0108: 'ImplicitInBase.Method(int, System.Func<int, int>, params int[])' hides inherited member 'Base.Method(int, System.Func<int, int>, int[])'. Use the new keyword if hiding was intended. // public int Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine("int Method(int x, Func<int, int> v, params int[] y)"); return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("ImplicitInBase.Method(int, System.Func<int, int>, params int[])", "Base.Method(int, System.Func<int, int>, int[])"), // (34,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method(T, U[])' and 'I1<T, U>.Method(U, params T[])' // i.Method(x, new int[] { x, x, x }); i.Method(x, x, x, x); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("I1<T, U>.Method(T, U[])", "I1<T, U>.Method(U, params T[])"), // (35,9): error CS0121: The call is ambiguous between the following methods or properties: 'I1<T, U>.Method(T, System.Func<T, U>, U[])' and 'I1<T, U>.Method(U, System.Func<T, U>, params U[])' // i.Method(x, y, new int[] { x, x, x }); i.Method(x, y, x, x, x); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("I1<T, U>.Method(T, System.Func<T, U>, U[])", "I1<T, U>.Method(U, System.Func<T, U>, params U[])")); } [Fact] public void TestImplementAmbiguousSignaturesFromSameInterface_Errors4() { var source = @" using System; interface I1<T, U> { Action<T> Method(ref T x); Action<U> Method(U x); // Omit ref void Method(ref Func<U, T> v); void Method(out Func<T, U> v); // Toggle ref to out void Method(T x, U[] y); void Method(U x, params T[] y); // Add params long Method(T x, Func<T, U> v, U[] y); int Method(U x, Func<T, U> v, params U[] y); // Add params and change return type } class Explicit : I1<int, int> { Action<int> I1<int, int>.Method(ref int x) { Console.WriteLine(""I1<int, int>.Method(ref int x)""); return null; } Action<int> I1<int, int>.Method(int x) { Console.WriteLine(""I1<int, int>.Method(int x)""); return null; } void I1<int, int>.Method(ref Func<int, int> v) { Console.WriteLine(""I1<int, int>.Method(ref Func<int, int> v)""); } void I1<int, int>.Method(out Func<int, int> v) { v = null; Console.WriteLine(""I1<int, int>.Method(out Func<int, int> v)""); } void I1<int, int>.Method(int x, int[] y) { Console.WriteLine(""I1<int, int>.Method(int x, int[] y)""); } // This has to be implicit so as not to clash with the above public void Method(int x, params int[] y) { Console.WriteLine(""Method(int x, params int[] y)""); } long I1<int, int>.Method(int x, Func<int, int> v, int[] y) { Console.WriteLine(""long I1<int, int>.Method(int x, Func<int, int> v, int[] y)""); return 0; } int I1<int, int>.Method(int x, Func<int, int> v, params int[] y) { Console.WriteLine(""int I1<int, int>.Method(int x, Func<int, int> v, params int[] y)""); return 0; } } class Test { public static void Main() { I1<int, int> i = new Explicit(); int x = 1; Func<int, int> y = null; i.Method(ref x); i.Method(x); i.Method(ref y); i.Method(out y); i.Method(x, x, x, x); i.Method(x, y, x, x, x); } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(ref System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(ref System.Func<int, int>)"), // (3,11): error CS0767: "Cannot inherit interface 'I1<int, int>' with the specified type parameters because it causes method 'I1<int, int>.Method(out System.Func<int, int>)' to contain overloads which differ only on ref and out." Diagnostic(ErrorCode.ERR_ExplicitImplCollisionOnRefOut, "I1").WithArguments("I1<int, int>", "I1<int, int>.Method(out System.Func<int, int>)"), // (20,23): warning CS0473: Explicit interface implementation 'Explicit.I1<int, int>.Method(int, int[])' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Explicit.I1<int, int>.Method(int, int[])")); } [Fact] public void TestErrorsOverridingImplementingMember() { // Tests: // Members that implement interface members are usually marked as virtual sealed - // test the errors that are reported when trying to override these implementing members var source = @" interface I { void M(); int P { set; } } class Base : I { public void M() { } public int P { set { } } } class Derived : Base { public override void M() { } public override int P { set { } } } class Base2 { public void M() { } public int P { set { } } } class Derived2 : Base2, I { } class Derived3 : Derived2 { public override void M() { } public override int P { set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (14,26): error CS0506: 'Derived.M()': cannot override inherited member 'Base.M()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M").WithArguments("Derived.M()", "Base.M()"), // (15,25): error CS0506: 'Derived.P': cannot override inherited member 'Base.P' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("Derived.P", "Base.P"), // (27,26): error CS0506: 'Derived3.M()': cannot override inherited member 'Base2.M()' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M").WithArguments("Derived3.M()", "Base2.M()"), // (28,25): error CS0506: 'Derived3.P': cannot override inherited member 'Base2.P' because it is not marked virtual, abstract, or override Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("Derived3.P", "Base2.P")); } [Fact] public void TestImplementingMethodNamedFinalize() { var source = @" interface I { void Finalize(); } class C1 : I { public void Finalize() { } } class C2 : I { } class Test { public static void Main() { I i = new C1(); i.Finalize(); } }"; CreateCompilation(source).VerifyDiagnostics( // (4,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize(); Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize").WithLocation(4, 10), // (6,28): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // class C1 : I { public void Finalize() { } } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize").WithLocation(6, 28), // (7,12): error CS0737: 'C2' does not implement interface member 'I.Finalize()'. 'object.~Object()' cannot implement an interface member because it is not public. // class C2 : I { } Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I").WithArguments("C2", "I.Finalize()", "object.~Object()").WithLocation(7, 12)); } [Fact] public void TestImplementingMethodNamedFinalize2() { var source = @" interface I { int Finalize(); void Finalize(int i); } class Base { public void Finalize(int j) { } } class Derived : Base, I { public int Finalize() { return 0; } } class Test { public static void Main() { I i = new Derived(); i.Finalize(i.Finalize()); } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitMethodImplementation() { var source = @" interface T { void T<S>(); } class A<T> : global::T { void T.T<S>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (8,10): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T<S>()' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T<S>()")); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitPropertyImplementation() { var source = @" interface T { int T { get; set; } } class A<T> : global::T { int T.T { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T")); } [WorkItem(542361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542361")] [Fact] public void TestTypeParameterExplicitEventImplementation() { var source = @" interface T { event System.Action T; } class A<T> : global::T { event System.Action T.T { add { } remove { } } }"; CreateCompilation(source).VerifyDiagnostics( // (8,25): error CS0538: 'T' in explicit interface declaration is not an interface Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "T").WithArguments("T"), // (6,7): error CS0535: 'A<T>' does not implement interface member 'T.T' Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "global::T").WithArguments("A<T>", "T.T")); } private static CSharpCompilation CompileAndVerifyDiagnostics(string text, ErrorDescription[] expectedErrors, params CSharpCompilation[] baseCompilations) { var refs = new List<MetadataReference>(baseCompilations.Select(c => new CSharpCompilationReference(c))); var comp = CreateCompilation(text, refs); var actualErrors = comp.GetDiagnostics(); //ostensibly, we could just pass exactMatch: true to VerifyErrorCodes, but that method is short-circuited when 0 errors are expected Assert.Equal(expectedErrors.Length, actualErrors.Count()); DiagnosticsUtils.VerifyErrorCodes(actualErrors, expectedErrors); return comp; } private static CSharpCompilation CompileAndVerifyDiagnostics(string text1, string text2, ErrorDescription[] expectedErrors1, ErrorDescription[] expectedErrors2) { var comp1 = CompileAndVerifyDiagnostics(text1, expectedErrors1); var comp2 = CompileAndVerifyDiagnostics(text2, expectedErrors2, comp1); return comp2; } [Fact] [WorkItem(1016693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016693")] public void Bug1016693() { const string source = @" public class A { public virtual int P { get; set; } public class B : A { public override int P { get; set; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(31974, "https://github.com/dotnet/roslyn/issues/31974")] public void Issue31974() { const string source = @" namespace Ns1 { public interface I1<I1T1> { void M(); int P {get; set;} event System.Action E; } public class C0<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C0<I2T1, I2T2>> { } class C1<C1T1, C1T2> : I2<C1T1, C1T2> { void I1<C0<C1T1, C1T2>>.M() { } void global::Ns1.I1<C0<C1T1, C1T2>>.M() { } int I1<C0<C1T1, C1T2>>.P { get => throw null; set => throw null; } int global::Ns1.I1<C0<C1T1, C1T2>>.P { get => throw null; set => throw null; } event System.Action I1<C0<C1T1, C1T2>>.E { add => throw null; remove => throw null; } event System.Action global::Ns1.I1<C0<C1T1, C1T2>>.E { add => throw null; remove => throw null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.P' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.P").WithLocation(18, 11), // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.E' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.E").WithLocation(18, 11), // (18,11): error CS8646: 'I1<C0<C1T1, C1T2>>.M()' is explicitly implemented more than once. // class C1<C1T1, C1T2> : I2<C1T1, C1T2> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("Ns1.I1<Ns1.C0<C1T1, C1T2>>.M()").WithLocation(18, 11) ); } [Fact] public void DynamicMismatch_01() { var source = @" public interface I0<T> { } public interface I1 : I0<object> { } public interface I2 : I0<dynamic> { } public interface I3 : I0<object> { } public class C : I1, I2 { } public class D : I1, I3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,23): error CS1966: 'I2': cannot implement a dynamic interface 'I0<dynamic>' // public interface I2 : I0<dynamic> { } Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("I2", "I0<dynamic>").WithLocation(4, 23), // (7,14): error CS8779: 'I0<dynamic>' is already listed in the interface list on type 'C' as 'I0<object>'. // public class C : I1, I2 { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, "C").WithArguments("I0<dynamic>", "I0<object>", "C").WithLocation(7, 14) ); } [Fact] public void DynamicMismatch_02() { var source = @" public interface I0<T> { void M(); } public class C : I0<object> { void I0<object>.M(){} } public class D : C, I0<dynamic> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,21): error CS1966: 'D': cannot implement a dynamic interface 'I0<dynamic>' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("D", "I0<dynamic>").WithLocation(11, 21), // (11,21): error CS0535: 'D' does not implement interface member 'I0<dynamic>.M()' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0<dynamic>").WithArguments("D", "I0<dynamic>.M()").WithLocation(11, 21) ); } [Fact] public void DynamicMismatch_03() { var source = @" public interface I0<T> { void M(); } public class C : I0<object> { void I0<object>.M(){} public void M(){} } public class D : C, I0<dynamic> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,21): error CS1966: 'D': cannot implement a dynamic interface 'I0<dynamic>' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I0<dynamic>").WithArguments("D", "I0<dynamic>").WithLocation(12, 21), // (12,21): error CS0535: 'D' does not implement interface member 'I0<dynamic>.M()' // public class D : C, I0<dynamic> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I0<dynamic>").WithArguments("D", "I0<dynamic>.M()").WithLocation(12, 21) ); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter1() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter2() { var source = @" interface I { void Goo<T>(T?[] value) where T : struct; } class C1 : I { public void Goo<T>(T?[] value) where T : struct { } } class C2 : I { void I.Goo<T>(T?[] value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter3() { var source = @" interface I { void Goo<T>((T a, T? b)? value) where T : struct; } class C1 : I { public void Goo<T>((T a, T? b)? value) where T : struct { } } class C2 : I { void I.Goo<T>((T a, T? b)? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); var tuple = c2Goo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct1() { var source = @" interface I { T? Goo<T>() where T : struct; } class C1 : I { public T? Goo<T>() where T : struct => default; } class C2 : I { T? I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct2() { var source = @" interface I { T?[] Goo<T>() where T : struct; } class C1 : I { public T?[] Goo<T>() where T : struct => default; } class C2 : I { T?[] I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.ReturnType).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodReturningNullableStructParameter_WithMethodReturningNullableStruct3() { var source = @" interface I { (T a, T? b)? Goo<T>() where T : struct; } class C1 : I { public (T a, T? b)? Goo<T>() where T : struct => default; } class C2 : I { (T a, T? b)? I.Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); var tuple = c2Goo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter1() { var source = @" abstract class Base { public abstract void Goo<T>(T? value) where T : struct; } class Derived : Base { public override void Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter2() { var source = @" abstract class Base { public abstract void Goo<T>(T?[] value) where T : struct; } class Derived : Base { public override void Goo<T>(T?[] value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter3() { var source = @" abstract class Base { public abstract void Goo<T>((T a, T? b)? value) where T : struct; } class Derived : Base { public override void Goo<T>((T a, T? b)? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct1() { var source = @" abstract class Base { public abstract T? Goo<T>() where T : struct; } class Derived : Base { public override T? Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct2() { var source = @" abstract class Base { public abstract T?[] Goo<T>() where T : struct; } class Derived : Base { public override T?[] Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.ReturnType).ElementType.IsNullableType()); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodReturningNullableStructParameter_WithMethodReturningNullableStruct3() { var source = @" abstract class Base { public abstract (T a, T? b)? Goo<T>() where T : struct; } class Derived : Base { public override (T a, T? b)? Goo<T>() => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); var tuple = dGoo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.False(tuple.TupleElements[0].Type.IsNullableType()); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] public void ImplementMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter_WithStructConstraint() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T? value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (14,29): error CS8652: The feature 'constraints for override and explicit interface implementation methods' is not available in C# 7.3. Please use language version 8.0 or greater. // void I.Goo<T>(T? value) where T : struct { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "where").WithArguments("constraints for override and explicit interface implementation methods", "8.0").WithLocation(14, 29) ); } [Fact] public void OverrideMethodTakingNullableStructParameter_WithMethodTakingNullableStructParameter_WithStructConstraint() { var source = @" abstract class Base { public abstract void Goo<T>(T? value) where T : struct; } class Derived : Base { public override void Goo<T>(T? value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); } [Fact] public void AllowStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(); CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,42): error CS8652: The feature 'constraints for override and explicit interface implementation methods' is not available in C# 7.3. Please use language version 8.0 or greater. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "where").WithArguments("constraints for override and explicit interface implementation methods", "8.0").WithLocation(9, 42) ); } [Fact] public void ErrorIfNonExistentTypeParameter_HasStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfNonExistentTypeParameter_HasClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasStructConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived<U> : Base { public override void Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived<U>.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived<U>.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasClassConstraintInOverride() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived<U> : Base { public override void Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,48): error CS0699: 'Derived<U>.Goo<T>(T)' does not define type parameter 'U' // public override void Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "Derived<U>.Goo<T>(T)").WithLocation(9, 48)); } [Fact] public void AllowStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AllowClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value) where T : class; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void ErrorIfNonExistentTypeParameter_HasStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C : I { void I.Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfNonExistentTypeParameter_HasClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C : I { void I.Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasStructConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C<U> : I { void I.Goo<T>(T value) where U : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C<U>.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : struct { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C<U>.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfTypeParameterDeclaredOutsideMethod_HasClassConstraintInExplicitInterfaceImplementation() { var source = @" interface I { void Goo<T>(T value); } class C<U> : I { void I.Goo<T>(T value) where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,34): error CS0699: 'C<U>.I.Goo<T>(T)' does not define type parameter 'U' // void I.Goo<T>(T value) where U : class { } Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "C<U>.I.Goo<T>(T)").WithLocation(9, 34)); } [Fact] public void ErrorIfNonExistentTypeParameter() { var source = @" interface I { void Goo(); } class C : I { void I.Goo() where U : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,18): error CS0080: Constraints are not allowed on non-generic declarations // void I.Goo() where U : class { } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(9, 18) ); } [Fact] public void ErrorIfDuplicateConstraintClause() { var source = @" interface I { void Goo<T>(T? value) where T : struct; } class C<U> : I { void I.Goo<T>(T? value) where T : struct where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. // void I.Goo<T>(T? value) where T : struct where T : class { } Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints1() { var source = @" abstract class Base { } class Derived : Base { public override void Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0115: 'Derived.Goo<T>(T)': no suitable method found to override // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Goo").WithArguments("Derived.Goo<T>(T)").WithLocation(8, 26), // (8,60): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 60)); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints2() { var source = @" abstract class Base { } class Derived : Base { public override void Goo<T>(T value) where T : class, struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0115: 'Derived.Goo<T>(T)': no suitable method found to override // public override void Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Goo").WithArguments("Derived.Goo<T>(T)").WithLocation(8, 26), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 59)); } [Fact] public void Error_WhenOverride_HasStructAndClassConstraints3() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,60): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public override void Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(9, 60)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints1() { var source = @" interface I { } class C : I { void I.Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0539: 'C.Goo<T>(T)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C.Goo<T>(T)").WithLocation(8, 12), // (8,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 46)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints2() { var source = @" interface I { } class C : I { void I.Goo<T>(T value) where T : class, struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0539: 'C.Goo<T>(T)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C.Goo<T>(T)").WithLocation(8, 12), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : class, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 45)); } [Fact] public void Error_WhenExplicitImplementation_HasStructAndClassConstraints3() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : struct, class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void I.Goo<T>(T value) where T : struct, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(9, 46)); } [Fact] public void Error_WhenOverride_HasNullableClassConstraint() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T value) where T : class?; } class Derived : Base { public override void Goo<T>(T value) where T : class? { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class? { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 52)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasNullableClassConstraint() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class?; } class C : I { void I.Goo<T>(T value) where T : class? { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,38): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : class? { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 38)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint1() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 52)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint2() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : class, Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,59): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class, Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 59)); } [Fact] public void Error_WhenOverride_HasReferenceTypeConstraint3() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T, U>(T value) where T : class where U : Stream; } class Derived : Base { public override void Goo<T, U>(T value) where T : class where U : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,71): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T, U>(T value) where T : class where U Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 71)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint1() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,38): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 38)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint2() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : class, Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T>(T value) where T : class, Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 45)); } [Fact] public void Error_WhenExplicitInterfaceImplementation_HasReferenceTypeConstraint3() { var source = @" using System.IO; interface I { void Goo<T, U>(T value) where T : class where U : Stream; } class C : I { void I.Goo<T, U>(T value) where T : class where U : Stream { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,57): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void I.Goo<T, U>(T value) where T : class where U : Stream { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "Stream").WithLocation(10, 57)); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot1() { var source = @" interface I { void Goo<U>(U value); } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I.Goo<U>(U)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "U", "I.Goo<U>(U)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot2() { var source = @" interface I { void Goo<T>(T value) where T : class; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasStructConstraint_AndInterfaceDoesNot3() { var source = @" using System.IO; interface I { void Goo<T>(T value) where T : Stream; } class C : I { void I.Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,16): error CS8666: Method 'C.I.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a non-nullable value type. // void I.Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(10, 16) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot1() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenDoesNot3() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot1() { var source = @" interface I { void Goo<U>(U value); } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I.Goo<U>(U)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "U", "I.Goo<U>(U)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot2() { var source = @" interface I { void Goo<T>(T value) where T : struct; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(9, 16) ); } [Fact] public void Error_WhenExplicitInterfaceImplementationHasClassConstraint_AndInterfaceDoesNot3() { var source = @" using System; interface I { void Goo<T>(T value) where T : Enum; } class C : I { void I.Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,16): error CS8665: Method 'C.I.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'I.Goo<T>(T)' is not a reference type. // void I.Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("C.I.Goo<T>(T)", "T", "T", "I.Goo<T>(T)").WithLocation(10, 16) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot1() { var source = @" abstract class Base { public abstract void Goo<T>(T value); } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : struct; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void Error_WhenOverrideHasClassConstraint_AndOverriddenDoesNot3() { var source = @" using System; abstract class Base { public abstract void Goo<T>(T value) where T : Enum; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8665: Method 'Derived.Goo<T>(T)' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a reference type. // public override void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenHasEnumConstraint() { var source = @" using System; abstract class Base { public abstract void Goo<T>(T value) where T : Enum; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base.Goo<T>(T)").WithLocation(10, 30) ); } [Fact] public void Error_WhenOverrideHasStructConstraint_AndOverriddenHasNullableConstraint() { var source = @" abstract class Base<U> { public abstract void Goo<T>(T value) where T : U; } class Derived : Base<int?> { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,30): error CS8666: Method 'Derived.Goo<T>(T)' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'Base<int?>.Goo<T>(T)' is not a non-nullable value type. // public override void Goo<T>(T value) where T : struct { } Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("Derived.Goo<T>(T)", "T", "T", "Base<int?>.Goo<T>(T)").WithLocation(9, 30) ); } [Fact] public void NoError_WhenOverrideHasStructConstraint_AndOverriddenHasUnmanagedConstraint() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged; } class Derived : Base { public override void Goo<T>(T value) where T : struct { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NoError_WhenOverrideHasClassConstraint_AndOverriddenHasReferenceTypeConstraint() { var source = @" using System.IO; abstract class Base { public abstract void Goo<T>(T value) where T : Stream; } class Derived : Base { public override void Goo<T>(T value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void Error_WhenOverride_HasDefaultConstructorConstraint1() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : new(); } class Derived : Base { public override void Goo<T>(T value) where T : new() { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : new() { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "new()").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasDefaultConstructorConstraint2() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : class, new(); } class Derived : Base { public override void Goo<T>(T value) where T : class, new() { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,59): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : class, new() { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "new()").WithLocation(9, 59) ); } [Fact] public void Error_WhenOverride_HasUnmanagedConstraint1() { var source = @" abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged; } class Derived : Base { public override void Goo<T>(T value) where T : unmanaged { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(9, 52) ); } [Fact] public void Error_WhenOverride_HasUnmanagedConstraint2() { var source = @" interface I {} abstract class Base { public abstract void Goo<T>(T value) where T : unmanaged, I; } class Derived : Base { public override void Goo<T>(T value) where T : unmanaged, I { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (11,52): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void Goo<T>(T value) where T : unmanaged, I { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(11, 52) ); } [Fact] [WorkItem(34583, "https://github.com/dotnet/roslyn/issues/34583")] public void ExplicitImplementationOfNullableStructWithMultipleTypeParameters() { var source = @" interface I { void Goo<T, U>(T? value) where T : struct; } class C1 : I { public void Goo<T, U>(T? value) where T : struct {} } class C2 : I { void I.Goo<T, U>(T? value) {} } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenDynamicTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGen_DynamicTests : CSharpTestBase { #region Helpers private CompilationVerifier CompileAndVerifyIL( string source, string methodName, string expectedOptimizedIL = null, string expectedUnoptimizedIL = null, MetadataReference[] references = null, bool allowUnsafe = false, [CallerFilePath] string callerPath = null, [CallerLineNumber] int callerLine = 0, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes) { references = references ?? new[] { SystemCoreRef, CSharpRef }; // verify that we emit correct optimized and unoptimized IL: var unoptimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe)); var optimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe)); var unoptimizedVerifier = CompileAndVerify(unoptimizedCompilation, verify: verify); var optimizedVerifier = CompileAndVerify(optimizedCompilation, verify: verify); // check what IL we emit exactly: if (expectedUnoptimizedIL != null) { unoptimizedVerifier.VerifyIL(methodName, expectedUnoptimizedIL, realIL: true, sequencePoints: methodName, callerPath: callerPath, callerLine: callerLine); } if (expectedOptimizedIL != null) { optimizedVerifier.VerifyIL(methodName, expectedOptimizedIL, realIL: true, callerPath: callerPath, callerLine: callerLine); } // return null if ambiguous return (expectedUnoptimizedIL != null) ^ (expectedOptimizedIL != null) ? (unoptimizedVerifier ?? optimizedVerifier) : null; } private readonly CSharpParseOptions _localFunctionParseOptions = TestOptions.Regular; #endregion #region C# Runtime and System.Core sources private const string CSharpBinderTemplate = @" using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Microsoft.CSharp.RuntimeBinder {{ {0} }} "; private const string CSharpBinderFlagsSource = @" public enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256 } "; private const string CSharpArgumentInfoFlagsSource = @" public enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32 } "; private const string CSharpArgumentInfoSource = @" public sealed class CSharpArgumentInfo { public static CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name) { return null; } } "; private readonly string[] _binderFactoriesSource = new[] { "CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context)", "CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context)", "CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", }; private MetadataReference MakeCSharpRuntime(string excludeBinder = null, bool excludeBinderFlags = false, bool excludeArgumentInfoFlags = false, MetadataReference systemCore = null) { var sb = new StringBuilder(); sb.AppendLine(excludeBinderFlags ? "public enum CSharpBinderFlags { A }" : CSharpBinderFlagsSource); sb.AppendLine(excludeArgumentInfoFlags ? "public enum CSharpArgumentInfoFlags { A }" : CSharpArgumentInfoFlagsSource); sb.AppendLine(CSharpArgumentInfoSource); foreach (var src in excludeBinder == null ? _binderFactoriesSource : _binderFactoriesSource.Where(src => src.IndexOf(excludeBinder, StringComparison.Ordinal) == -1)) { sb.AppendFormat("public partial class Binder {{ public static {0} {{ return null; }} }}", src); sb.AppendLine(); } string source = string.Format(CSharpBinderTemplate, sb.ToString()); return CreateCompilationWithMscorlib40(source, new[] { systemCore ?? SystemCoreRef }, assemblyName: GetUniqueName()).EmitToImageReference(); } private const string ExpressionTypeSource = @" namespace System.Linq.Expressions { public enum ExpressionType { Add, AddChecked, And, AndAlso, ArrayLength, ArrayIndex, Call, Coalesce, Conditional, Constant, Convert, ConvertChecked, Divide, Equal, ExclusiveOr, GreaterThan, GreaterThanOrEqual, Invoke, Lambda, LeftShift, LessThan, LessThanOrEqual, ListInit, MemberAccess, MemberInit, Modulo, Multiply, MultiplyChecked, Negate, UnaryPlus, NegateChecked, New, NewArrayInit, NewArrayBounds, Not, NotEqual, Or, OrElse, Parameter, Power, Quote, RightShift, Subtract, SubtractChecked, TypeAs, TypeIs, Assign, Block, DebugInfo, Decrement, Dynamic, Default, Extension, Goto, Increment, Index, Label, RuntimeVariables, Loop, Switch, Throw, Try, Unbox, AddAssign, AndAssign, DivideAssign, ExclusiveOrAssign, LeftShiftAssign, ModuloAssign, MultiplyAssign, OrAssign, PowerAssign, RightShiftAssign, SubtractAssign, AddAssignChecked, MultiplyAssignChecked, SubtractAssignChecked, PreIncrementAssign, PreDecrementAssign, PostIncrementAssign, PostDecrementAssign, TypeEqual, OnesComplement, IsTrue, IsFalse } } "; private const string DynamicAttributeSource = @" namespace System.Runtime.CompilerServices { public sealed class DynamicAttribute : Attribute { public DynamicAttribute() { } public DynamicAttribute(bool[] transformFlags) { } } }"; private const string CallSiteSource = @" namespace System.Runtime.CompilerServices { public class CallSite { } public class CallSite<T> : CallSite where T : class { public T Target; public static CallSite<T> Create(CallSiteBinder binder) { return null; } } public abstract class CallSiteBinder { } }"; private const string SystemCoreSource = ExpressionTypeSource + DynamicAttributeSource + CallSiteSource; #endregion #region Missing Well-Known Members [Fact] public void Missing_CSharpArgumentInfo() { string source = @" class C { public event System.Action e; public C(dynamic d) { } void F(dynamic d) { var a1 = d * d; var a2 = (int)d; var a3 = d[d]; var a4 = d.M; var a5 = d(); var a6 = d.M(); var a7 = new C(d); e += d; var a9 = d[d] = d; var a10 = d.M = d; var a11 = -d; e(); } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics( // (9,18): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // var a1 = d * d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(9, 18) ); } [Fact] public void Missing_Binder() { var csrtRef = MakeCSharpRuntime(excludeBinder: "InvokeConstructor"); string source = @" class C { public C(int a) { } void F(dynamic d) { new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M)); } } "; CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (8,9): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor' // new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M))").WithArguments("Microsoft.CSharp.RuntimeBinder.Binder", "InvokeConstructor") ); } [Fact] public void Missing_Flags() { var csrtRef = MakeCSharpRuntime(excludeBinderFlags: true, excludeArgumentInfoFlags: true); string source = @" class C { public static void G(int a) { } void F(dynamic d) { G(d); // CSharpBinderFlags.InvokeSimpleName, CSharpBinderFlags.ResultDiscarded // CSharpArgumentInfoFlags.None, CSharpArgumentInfoFlags.UseCompileTimeType } } "; // the compiler ignores the enum values, uses hardcoded values: CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef, csrtRef }).VerifyEmitDiagnostics(); } [Fact] public void Missing_Func() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // the delegate is generated, no error is reported CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }); } [Fact] public void InvalidFunc_Arity() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); var funcRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.InvalidFuncDelegateName.AsImmutableOrNull()); string source = @" class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // the delegate is generated, no error is reported var c = CompileAndVerifyWithMscorlib40(source, new[] { systemCoreRef, csrtRef, funcRef }); Assert.Equal(1, ((CSharpCompilation)c.Compilation).GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMember<NamedTypeSymbol>("Func`13").Arity); } [Fact, WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void InvalidFunc_Constraints() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" namespace System { public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12) where T4 : class; } class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // Desired: the delegate is generated, no error is reported. // Actual: use the malformed Func`13 time and failed to PEVerify. Not presently worthwhile to fix. CompileAndVerifyWithMscorlib40(source, new[] { systemCoreRef, csrtRef }, verify: Verification.Fails).VerifyIL("C.F", @" { // Code size 189 (0xbd) .maxstack 13 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_009b IL_000a: ldc.i4.0 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldc.i4.s 11 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.3 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.4 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.5 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.6 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.7 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.8 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.s 9 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.s 10 IL_0084: ldc.i4.3 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0091: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0096: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_00a0: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>>.Target"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_00aa: ldarg.1 IL_00ab: ldc.i4.1 IL_00ac: ldc.i4.2 IL_00ad: ldc.i4.3 IL_00ae: ldc.i4.4 IL_00af: ldc.i4.5 IL_00b0: ldc.i4.6 IL_00b1: ldc.i4.7 IL_00b2: ldc.i4.8 IL_00b3: ldc.i4.s 9 IL_00b5: ldc.i4.s 10 IL_00b7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int)"" IL_00bc: ret } "); } [Fact] public void Missing_CallSite() { string systemCoreSource = ExpressionTypeSource + DynamicAttributeSource + @" namespace System.Runtime.CompilerServices { public class CallSite<T> where T : class { public T Target; public static CallSite<T> Create(CallSiteBinder binder) { return null; } } public abstract class CallSiteBinder { } }"; var systemCoreRef = CreateCompilationWithMscorlib40(systemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d * d; } } "; CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.CallSite' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Runtime.CompilerServices.CallSite"), // error CS1969: One or more types required to compile a dynamic expression cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicRequiredTypesMissing)); } [Fact] public void Missing_CallSiteOfT() { string systemCoreSource = ExpressionTypeSource + DynamicAttributeSource + @" namespace System.Runtime.CompilerServices { public class CallSite { } public class CallSiteBinder {} }"; var systemCoreRef = CreateCompilationWithMscorlib40(systemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d * d; } } "; CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.CallSite`1' is not defined or imported // return d * d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Runtime.CompilerServices.CallSite`1").WithLocation(6, 16), // (6,16): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.CallSite`1.Create' // return d * d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("System.Runtime.CompilerServices.CallSite`1", "Create").WithLocation(6, 16) ); } #endregion #region Generated Metadata (call-site containers, delegates) /// <summary> /// Dev11 doesn't include name of explicit interface implementation method into site container name. /// </summary> [Fact] public void ExplicitInterfaceImplementation() { string source = @" public interface I { dynamic M(dynamic d); } public class C : I { dynamic I.M(dynamic d) { return checked(d * d); } }"; CompileAndVerifyIL(source, "C.I.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void CallSiteContainers() { string source = @" public class C { public void M1(dynamic d) { d.m(1,2,3); } public void M2(dynamic d) { d.m(1,2,3); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var containers = c.GetMembers().OfType<NamedTypeSymbol>().ToArray(); Assert.Equal(2, containers.Length); foreach (var container in containers) { Assert.Equal(Accessibility.Private, container.DeclaredAccessibility); Assert.True(container.IsStatic); Assert.Equal(SpecialType.System_Object, container.BaseType().SpecialType); AssertEx.SetEqual(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(container.GetAttributes())); var members = container.GetMembers(); Assert.Equal(1, members.Length); var field = (FieldSymbol)members[0]; Assert.Equal(Accessibility.Public, field.DeclaredAccessibility); Assert.True(field.IsStatic); Assert.False(field.IsReadOnly); Assert.Equal("System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int>>", field.TypeWithAnnotations.ToDisplayString()); Assert.Equal(0, field.GetAttributes().Length); switch (container.Name) { case "<>o__0": Assert.Equal("<>p__0", field.Name); break; case "<>o__1": Assert.Equal("<>p__0", field.Name); break; default: throw TestExceptionUtilities.UnexpectedValue(container.Name); } } }); } [Fact] public void CallSiteContainers_MultipleSitesInMethod_DisplayClass() { string source = @" public class C { public void M1(dynamic d) { d.m(1); d.m(1,2); var x = new System.Action(() => d.m()); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(2, c.GetMembers().OfType<NamedTypeSymbol>().Count()); var container = c.GetMember<NamedTypeSymbol>("<>o__0"); // all call-site storage fields of the method are added to a single container: var memberNames = container.GetMembers().Select(m => m.Name); AssertEx.SetEqual(new[] { "<>p__0", "<>p__1", "<>p__2" }, memberNames); var displayClass = c.GetMember<NamedTypeSymbol>("<>c__DisplayClass0_0"); var d = displayClass.GetMember<FieldSymbol>("d"); var attributes = d.GetAttributes(); Assert.Equal(1, attributes.Length); Assert.Equal("System.Runtime.CompilerServices.DynamicAttribute", attributes[0].AttributeClass.ToDisplayString()); }); } [Fact] public void Iterator() { string source = @" using System.Collections.Generic; public class C { public IEnumerable<dynamic> M1() { dynamic d = 1; yield return 1; d = d + 2; yield return d; } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var iteratorClass = c.GetMember<NamedTypeSymbol>("<M1>d__0"); foreach (var member in iteratorClass.GetMembers()) { switch (member.Kind) { case SymbolKind.Field: // no field is marked with DynamicAttribute Assert.Equal(0, member.GetAttributes().Length); break; case SymbolKind.Method: var attributes = ((MethodSymbol)member).GetReturnTypeAttributes(); switch (member.MetadataName) { case "System.Collections.Generic.IEnumerator<dynamic>.get_Current": case "System.Collections.Generic.IEnumerable<dynamic>.GetEnumerator": Assert.Equal(1, attributes.Length); break; default: Assert.Equal(0, attributes.Length); break; } break; case SymbolKind.Property: // "Current" properties or return types are not marked with attributes break; default: throw TestExceptionUtilities.UnexpectedValue(member.Kind); } } var container = c.GetMember<NamedTypeSymbol>("<>o__0"); Assert.Equal(1, container.GetMembers().Length); }); } [Fact] [WorkItem(625282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625282")] public void GenericIterator() { string source = @" using System.Collections.Generic; class C { dynamic d = null; public IEnumerable<T> Run<T>() { yield return d; } } "; CompileAndVerifyIL(source, "C.<Run>d__1<T>.System.Collections.IEnumerator.MoveNext", @" { // Code size 123 (0x7b) .maxstack 4 .locals init (int V_0, C V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Run>d__1<T>.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C C.<Run>d__1<T>.<>4__this"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: brfalse.s IL_0017 IL_0011: ldloc.0 IL_0012: ldc.i4.1 IL_0013: beq.s IL_0072 IL_0015: ldc.i4.0 IL_0016: ret IL_0017: ldarg.0 IL_0018: ldc.i4.m1 IL_0019: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_001e: ldarg.0 IL_001f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_0024: brtrue.s IL_004a IL_0026: ldc.i4.0 IL_0027: ldtoken ""T"" IL_002c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0031: ldtoken ""C"" IL_0036: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0040: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0045: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_004f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, T> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Target"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_0059: ldloc.1 IL_005a: ldfld ""dynamic C.d"" IL_005f: callvirt ""T System.Func<System.Runtime.CompilerServices.CallSite, object, T>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0064: stfld ""T C.<Run>d__1<T>.<>2__current"" IL_0069: ldarg.0 IL_006a: ldc.i4.1 IL_006b: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_0070: ldc.i4.1 IL_0071: ret IL_0072: ldarg.0 IL_0073: ldc.i4.m1 IL_0074: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_0079: ldc.i4.0 IL_007a: ret } "); } [Fact] public void NoDynamicAttributeOnCallSiteStorageField() { string source = @" using System.Collections.Generic; public class C { public dynamic M(dynamic d, List<dynamic> a, Dictionary<dynamic, dynamic[]>[] b) { return d(a, b); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var container = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("<>o__0"); Assert.Equal(0, container.GetMembers().Single().GetAttributes().Length); }); } [Fact] public void GeneratedDelegates() { string source = @" using System.Collections.Generic; public class C { public dynamic M(dynamic d) { return d(ref d); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var d = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("<>F{00000010}"); // the type: Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(4, d.TypeParameters.Length); Assert.True(d.IsSealed); Assert.Equal(CharSet.Ansi, d.MarshallingCharSet); Assert.Equal(SpecialType.System_MulticastDelegate, d.BaseType().SpecialType); Assert.Equal(0, d.Interfaces().Length); AssertEx.SetEqual(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(d.GetAttributes())); // members: var members = d.GetMembers(); Assert.Equal(2, members.Length); foreach (var member in members) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); switch (member.Name) { case ".ctor": Assert.False(member.IsStatic); Assert.False(member.IsSealed); Assert.False(member.IsVirtual); break; case "Invoke": Assert.False(member.IsStatic); Assert.False(member.IsSealed); Assert.True(member.IsVirtual); break; default: throw TestExceptionUtilities.UnexpectedValue(member.Name); } } }); } [Fact] public void GenericContainer1() { string source = @" public class C { public T M<T>(dynamic d) { return (T)d; } } "; CompileAndVerifyIL(source, "C.M<T>", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""T"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, T> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""T System.Func<System.Runtime.CompilerServices.CallSite, object, T>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret } "); } [Fact] public void GenericContainer2() { string source = @" public class E<P, Q, R> {} public class C<U> { public dynamic M<S,T>(dynamic d) { E<S, T, U> dict = null; return d(ref dict); } } "; CompileAndVerifyIL(source, "C<U>.M<S, T>", @" { // Code size 86 (0x56) .maxstack 7 .locals init (E<S, T, U> V_0) //dict IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""C<U>"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 9 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_004d: ldarg.1 IL_004e: ldloca.s V_0 IL_0050: callvirt ""object <>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref E<S, T, U>)"" IL_0055: ret } "); } [Fact] public void GenericContainer3() { string source = @" public class C<U> { public dynamic M(dynamic d) { return d(); } } "; CompileAndVerifyIL(source, "C<U>.M", @" { // Code size 71 (0x47) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0031 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C<U>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.1 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0040: ldarg.1 IL_0041: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: ret } "); } [Fact] public void GenericContainer4() { string source = @" using System; class C { public static int F<T>(dynamic d, Type t, T x) where T : struct { if (d.GetType() == t && ((T)d).Equals(x)) { return 1; } return 2; } } "; CompileAndVerifyWithCSharp(source); } [Fact] [WorkItem(627091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627091")] public void GenericContainer_Lambda() { string source = @" class C { static void Goo<T>(T a, dynamic b) { System.Action f = () => Goo(a, b); } } "; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0<T>.<Goo>b__0", @" { // Code size 123 (0x7b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0005: brtrue.s IL_0050 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.3 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.1 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.0 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0046: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0055: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>>.Target"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_005f: ldtoken ""C"" IL_0064: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0069: ldarg.0 IL_006a: ldfld ""T C.<>c__DisplayClass0_0<T>.a"" IL_006f: ldarg.0 IL_0070: ldfld ""dynamic C.<>c__DisplayClass0_0<T>.b"" IL_0075: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, T, object)"" IL_007a: ret } "); } [Fact] public void DynamicErasure_MetadataConstant() { string source = @" public class C { const dynamic f = null; public void M(dynamic arg = null) { const dynamic local = null; } } "; CompileAndVerifyWithMscorlib40(source, new[] { SystemCoreRef }); } [Fact, WorkItem(16, "http://roslyn.codeplex.com/workitem/16")] public void RemoveAtOfKeywordAsDynamicMemberName() { string source = @" using System; class C { // field public int @default = 123; // prop protected string @if { get; set; } int @else { get { return 1; } } // event public event Action @event { add { } remove { } } // Method internal int @while(dynamic @void) { return 456; } static void Main() { dynamic dyn = new C(); if (dyn.@default == 123) { dynamic @static = 12; dyn.@default = dyn.@while(@static); } dyn.@if = [email protected](); dyn.@event += (Action)( () => { dyn.@if = [email protected](); }); } } "; CompileAndVerifyIL(source, "C.Main", @" { // Code size 1130 (0x46a) .maxstack 13 .locals init (C.<>c__DisplayClass11_0 V_0, //CS$<>8__locals0 object V_1, //static object V_2, bool V_3, object V_4, System.Action V_5) IL_0000: newobj ""C.<>c__DisplayClass11_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj ""C..ctor()"" IL_000c: stfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_0011: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0016: brtrue.s IL_0044 IL_0018: ldc.i4.0 IL_0019: ldc.i4.s 83 IL_001b: ldtoken ""C"" IL_0020: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0025: ldc.i4.1 IL_0026: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0049: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0058: brtrue.s IL_0090 IL_005a: ldc.i4.0 IL_005b: ldc.i4.s 13 IL_005d: ldtoken ""C"" IL_0062: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0067: ldc.i4.2 IL_0068: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006d: dup IL_006e: ldc.i4.0 IL_006f: ldc.i4.0 IL_0070: ldnull IL_0071: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0076: stelem.ref IL_0077: dup IL_0078: ldc.i4.1 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0086: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0090: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0095: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00a4: brtrue.s IL_00d5 IL_00a6: ldc.i4.0 IL_00a7: ldstr ""default"" IL_00ac: ldtoken ""C"" IL_00b1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b6: ldc.i4.1 IL_00b7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bc: dup IL_00bd: ldc.i4.0 IL_00be: ldc.i4.0 IL_00bf: ldnull IL_00c0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c5: stelem.ref IL_00c6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00da: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00df: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00e4: ldloc.0 IL_00e5: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_00ea: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ef: ldc.i4.s 123 IL_00f1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00f6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00fb: brfalse IL_01bf IL_0100: ldc.i4.s 12 IL_0102: box ""int"" IL_0107: stloc.1 IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_010d: brtrue.s IL_0148 IL_010f: ldc.i4.0 IL_0110: ldstr ""default"" IL_0115: ldtoken ""C"" IL_011a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_011f: ldc.i4.2 IL_0120: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0125: dup IL_0126: ldc.i4.0 IL_0127: ldc.i4.0 IL_0128: ldnull IL_0129: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012e: stelem.ref IL_012f: dup IL_0130: ldc.i4.1 IL_0131: ldc.i4.0 IL_0132: ldnull IL_0133: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0138: stelem.ref IL_0139: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_013e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0143: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_0148: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_014d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0152: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_0157: ldloc.0 IL_0158: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_015d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_0162: brtrue.s IL_019e IL_0164: ldc.i4.0 IL_0165: ldstr ""while"" IL_016a: ldnull IL_016b: ldtoken ""C"" IL_0170: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0175: ldc.i4.2 IL_0176: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_017b: dup IL_017c: ldc.i4.0 IL_017d: ldc.i4.0 IL_017e: ldnull IL_017f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0184: stelem.ref IL_0185: dup IL_0186: ldc.i4.1 IL_0187: ldc.i4.0 IL_0188: ldnull IL_0189: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_018e: stelem.ref IL_018f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0194: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0199: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_019e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_01a3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_01a8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_01ad: ldloc.0 IL_01ae: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_01b3: ldloc.1 IL_01b4: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01b9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01be: pop IL_01bf: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_01c4: brtrue.s IL_01ff IL_01c6: ldc.i4.0 IL_01c7: ldstr ""if"" IL_01cc: ldtoken ""C"" IL_01d1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01d6: ldc.i4.2 IL_01d7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01dc: dup IL_01dd: ldc.i4.0 IL_01de: ldc.i4.0 IL_01df: ldnull IL_01e0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01e5: stelem.ref IL_01e6: dup IL_01e7: ldc.i4.1 IL_01e8: ldc.i4.0 IL_01e9: ldnull IL_01ea: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01ef: stelem.ref IL_01f0: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01f5: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01fa: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_01ff: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_0204: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0209: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_020e: ldloc.0 IL_020f: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_0214: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_0219: brtrue.s IL_024b IL_021b: ldc.i4.0 IL_021c: ldstr ""ToString"" IL_0221: ldnull IL_0222: ldtoken ""C"" IL_0227: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_022c: ldc.i4.1 IL_022d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0232: dup IL_0233: ldc.i4.0 IL_0234: ldc.i4.0 IL_0235: ldnull IL_0236: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_023b: stelem.ref IL_023c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0241: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0246: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_024b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_0250: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0255: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_025a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_025f: brtrue.s IL_0290 IL_0261: ldc.i4.0 IL_0262: ldstr ""else"" IL_0267: ldtoken ""C"" IL_026c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0271: ldc.i4.1 IL_0272: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0277: dup IL_0278: ldc.i4.0 IL_0279: ldc.i4.0 IL_027a: ldnull IL_027b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0280: stelem.ref IL_0281: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0286: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_028b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_0290: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_0295: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_029a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_029f: ldloc.0 IL_02a0: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_02a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02aa: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02af: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_02b4: pop IL_02b5: ldloc.0 IL_02b6: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_02bb: stloc.2 IL_02bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02c1: brtrue.s IL_02e2 IL_02c3: ldc.i4.0 IL_02c4: ldstr ""event"" IL_02c9: ldtoken ""C"" IL_02ce: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02d3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_02d8: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_02dd: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02e7: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_02ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02f1: ldloc.2 IL_02f2: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02f7: stloc.3 IL_02f8: ldloc.3 IL_02f9: brtrue.s IL_0348 IL_02fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0300: brtrue.s IL_0331 IL_0302: ldc.i4.0 IL_0303: ldstr ""event"" IL_0308: ldtoken ""C"" IL_030d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0312: ldc.i4.1 IL_0313: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0318: dup IL_0319: ldc.i4.0 IL_031a: ldc.i4.0 IL_031b: ldnull IL_031c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0321: stelem.ref IL_0322: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0327: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_032c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0331: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0336: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_033b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0340: ldloc.2 IL_0341: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0346: stloc.s V_4 IL_0348: ldloc.0 IL_0349: ldftn ""void C.<>c__DisplayClass11_0.<Main>b__0()"" IL_034f: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0354: stloc.s V_5 IL_0356: ldloc.3 IL_0357: brtrue IL_040c IL_035c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_0361: brtrue.s IL_03a0 IL_0363: ldc.i4 0x80 IL_0368: ldstr ""event"" IL_036d: ldtoken ""C"" IL_0372: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0377: ldc.i4.2 IL_0378: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_037d: dup IL_037e: ldc.i4.0 IL_037f: ldc.i4.0 IL_0380: ldnull IL_0381: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0386: stelem.ref IL_0387: dup IL_0388: ldc.i4.1 IL_0389: ldc.i4.0 IL_038a: ldnull IL_038b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0390: stelem.ref IL_0391: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0396: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_039b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03a5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_03aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03af: ldloc.2 IL_03b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03b5: brtrue.s IL_03ed IL_03b7: ldc.i4.0 IL_03b8: ldc.i4.s 63 IL_03ba: ldtoken ""C"" IL_03bf: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_03c4: ldc.i4.2 IL_03c5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_03ca: dup IL_03cb: ldc.i4.0 IL_03cc: ldc.i4.0 IL_03cd: ldnull IL_03ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_03d3: stelem.ref IL_03d4: dup IL_03d5: ldc.i4.1 IL_03d6: ldc.i4.1 IL_03d7: ldnull IL_03d8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_03dd: stelem.ref IL_03de: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_03e3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_03e8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03f2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Target"" IL_03f7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03fc: ldloc.s V_4 IL_03fe: ldloc.s V_5 IL_0400: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, System.Action)"" IL_0405: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_040a: pop IL_040b: ret IL_040c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0411: brtrue.s IL_0451 IL_0413: ldc.i4 0x104 IL_0418: ldstr ""add_event"" IL_041d: ldnull IL_041e: ldtoken ""C"" IL_0423: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0428: ldc.i4.2 IL_0429: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_042e: dup IL_042f: ldc.i4.0 IL_0430: ldc.i4.0 IL_0431: ldnull IL_0432: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0437: stelem.ref IL_0438: dup IL_0439: ldc.i4.1 IL_043a: ldc.i4.1 IL_043b: ldnull IL_043c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0441: stelem.ref IL_0442: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0447: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_044c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0451: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0456: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Target"" IL_045b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0460: ldloc.2 IL_0461: ldloc.s V_5 IL_0463: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, System.Action)"" IL_0468: pop IL_0469: ret } "); } #endregion #region Conversions [Fact] public void LocalFunctionArgumentConversion() { string src = @" using System; public class C { static void Main() { int capture1 = 0; void L1(int x) => Console.Write(x); Action<int> L2(int x) { Console.Write(capture1); Console.Write(x); void L3(int y) { Console.Write(y + x); } return L3; } dynamic d = 2; L1(d); dynamic l3 = L2(d); l3(d); } }"; CompileAndVerifyWithCSharp(src, expectedOutput: "2024", parseOptions: _localFunctionParseOptions).VerifyDiagnostics(); CompileAndVerifyIL(src, "C.Main", parseOptions: _localFunctionParseOptions, expectedOptimizedIL: @" { // Code size 242 (0xf2) .maxstack 7 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 object V_1, //d object V_2) //l3 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: stfld ""int C.<>c__DisplayClass0_0.capture1"" IL_0008: ldc.i4.2 IL_0009: box ""int"" IL_000e: stloc.1 IL_000f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0014: brtrue.s IL_003a IL_0016: ldc.i4.0 IL_0017: ldtoken ""int"" IL_001c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0021: ldtoken ""C"" IL_0026: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0030: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0035: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0049: ldloc.1 IL_004a: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004f: call ""void C.<Main>g__L1|0_0(int)"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0059: brtrue.s IL_007f IL_005b: ldc.i4.0 IL_005c: ldtoken ""int"" IL_0061: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0066: ldtoken ""C"" IL_006b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_008e: ldloc.1 IL_008f: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: ldloca.s V_0 IL_0096: call ""System.Action<int> C.<Main>g__L2|0_1(int, ref C.<>c__DisplayClass0_0)"" IL_009b: stloc.2 IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00a1: brtrue.s IL_00db IL_00a3: ldc.i4 0x100 IL_00a8: ldtoken ""C"" IL_00ad: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b2: ldc.i4.2 IL_00b3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b8: dup IL_00b9: ldc.i4.0 IL_00ba: ldc.i4.0 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: dup IL_00c3: ldc.i4.1 IL_00c4: ldc.i4.0 IL_00c5: ldnull IL_00c6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cb: stelem.ref IL_00cc: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00e0: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00ea: ldloc.2 IL_00eb: ldloc.1 IL_00ec: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f1: ret }"); } [Fact] public void Conversion_Assignment() { string source = @" public class C { dynamic d = null; void M() { int i = d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_003a: ldarg.0 IL_003b: ldfld ""dynamic C.d"" IL_0040: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0045: pop IL_0046: ret } "); } [Fact] public void Conversion_Implicit() { string source = @" public class C { public int M(dynamic d) { return d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret } "); } [Fact] public void Conversion_Explicit() { string source = @" public class C { public int M(dynamic d) { return (int)d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""int"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret }"); } [Fact] public void Conversion_Implicit_Checked() { string source = @" public class C { public int M(dynamic d) { checked { return d; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.1 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret }"); } [Fact] public void Conversion_Explicit_Checked() { string source = @" public class C { public int M(dynamic d) { checked { return (int)d; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 17 IL_0009: ldtoken ""int"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret }"); } [Fact] public void Conversion_Implicit_Reference_Return() { string source = @" class D { } class C { public D M(dynamic d) { return d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""D"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret } "); } [Fact] public void Conversion_Implicit_Reference_Assignment() { string source = @" class D { } class C { D x; public void M(dynamic d) { x = d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 71 (0x47) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""D"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: stfld ""D C.x"" IL_0046: ret } "); } [Fact] public void Conversion_Explicit_Reference() { string source = @" class D { } class C { public D M(dynamic d) { return (D)d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""D"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret } "); } [Fact] public void Conversion_ArrayIndex() { string source = @" public class C { public object M(object[] a, dynamic d) { return a[d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 32 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret } "); } [Fact] public void Conversion_ArrayIndex_Checked() { string source = @" public class C { public object M(object[] a, dynamic d) { return checked(a[d]); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 33 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret }"); } [Fact] public void Conversion_ArrayIndex_Explicit() { string source = @" public class C { public object M(object[] a, dynamic d) { return a[(int)d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret }"); } [Fact] public void IdentityConversion1() { string source = @" public class C { public object M(dynamic d) { return d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret } "); } [Fact] public void IdentityConversion2() { string source = @" public class C { public static void M() { dynamic d = new object(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: newobj ""object..ctor()"" IL_0005: pop IL_0006: ret } "); } [Fact] public void IdentityConversion3() { string source = @" public class C { public dynamic Null() { return null; } }"; CompileAndVerifyIL(source, "C.Null", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret } "); } [Fact] public void Boxing_ReturnValue() { string source = @" public class C { public dynamic Int32() { return 1; } }"; CompileAndVerifyIL(source, "C.Int32", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ret } "); } [Fact] public void Boxing_AssignmentToDynamicField1() { string source = @" class C { dynamic d; void M() { d = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: box ""bool"" IL_0007: stfld ""dynamic C.d"" IL_000c: ret } "); } [Fact] public void Boxing_AssignmentToDynamicField2() { string source = @" class C { dynamic d; void M() { new C { d = true }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.1 IL_0006: box ""bool"" IL_000b: stfld ""dynamic C.d"" IL_0010: ret } "); } [Fact] public void Boxing_AssignmentToDynamicIndex() { string source = @" class C { dynamic this[int i] { get { return 1; } set { } } void M() { this[1] = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: box ""bool"" IL_0008: call ""void C.this[int].set"" IL_000d: ret } "); } [Fact] public void Boxing_AssignmentToProperty1() { string source = @" class C { dynamic d { get; set; } void M() { this.d = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: box ""bool"" IL_0007: call ""void C.d.set"" IL_000c: ret } "); } [Fact] public void Boxing_AssignmentToProperty2() { string source = @" class C { dynamic d { get; set; } void M() { new C { d = true }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.1 IL_0006: box ""bool"" IL_000b: callvirt ""void C.d.set"" IL_0010: ret } "); } [Fact] public void IsAs() { string source = @" using System.Collections.Generic; public class C { public bool IsObject(dynamic d) { return d is List<object>; } public bool IsDynamic(dynamic d) { return d is List<dynamic>; } public List<dynamic> As(dynamic d) { return d as List<dynamic>; } }"; // TODO: Why does RefEmit use fat header with maxstack = 2? var verifier = CompileAndVerifyWithCSharp(source, symbolValidator: module => { var pe = (PEModuleSymbol)module; // all occurrences of List<dynamic> and List<object> should be unified to a single TypeSpec: Assert.Equal(1, pe.Module.GetMetadataReader().GetTableRowCount(TableIndex.TypeSpec)); }); verifier.VerifyIL("C.IsObject", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret } ", realIL: true); verifier.VerifyIL("C.IsDynamic", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret } ", realIL: true); verifier.VerifyIL("C.As", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ret } ", realIL: true); } [Fact] public void DelegateCreation() { string source = @" using System; public class C { dynamic d = null; Action a; public virtual void M() { a = new System.Action(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""System.Action"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_003b: ldarg.0 IL_003c: ldfld ""dynamic C.d"" IL_0041: callvirt ""System.Action System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: ldftn ""void System.Action.Invoke()"" IL_004c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0051: stfld ""System.Action C.a"" IL_0056: ret } "); } [Fact] public void TestThrowDynamic() { var source = @" using System; class C { public static void Main() { M(null); M(new Exception()); M(new ArgumentException()); M(string.Empty); } static void M(dynamic d) { try { throw d; } catch (Exception ex) { System.Console.WriteLine(ex.GetType().Name); } } } "; CompileAndVerifyWithCSharp(source, expectedOutput: @"NullReferenceException Exception ArgumentException RuntimeBinderException"); } #endregion #region Operators [Fact] public void Multiplication_Dynamic_Dynamic() { string source = @" public class C { public dynamic M(dynamic d) { return d * d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Multiplication_Dynamic_Static() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c * d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.1 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_0053: ret } "); } [Fact] public void Multiplication_Dynamic_Literal() { string source = @" public class C { public dynamic M(dynamic d) { return d * 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.3 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldc.i4.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0053: ret } "); } [Fact] public void Multiplication_Checked() { string source = @" public class C { public dynamic M(dynamic d) { return checked(d * d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Division() { string source = @" public class C { public dynamic M(dynamic d) { return d / d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 12 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Remainder() { string source = @" public class C { public dynamic M(dynamic d) { return d % d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 25 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void LeftShift() { string source = @" public class C { public dynamic M(dynamic d) { return d << d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 19 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void RightShift() { string source = @" public class C { public dynamic M(dynamic d) { return d >> d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 41 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void And() { string source = @" public class C { public dynamic M(dynamic d) { return d & d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 83 (0x53) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldc.i4.2 IL_0009: ldtoken ""C"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldc.i4.2 IL_0014: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0019: dup IL_001a: ldc.i4.0 IL_001b: ldc.i4.0 IL_001c: ldnull IL_001d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0022: stelem.ref IL_0023: dup IL_0024: ldc.i4.1 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0041: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004b: ldarg.1 IL_004c: ldarg.1 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0052: ret } "); } [Fact] public void Or() { string source = @" public class C { public dynamic M(dynamic d) { return d | d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 36 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Xor() { string source = @" public class C { public dynamic M(dynamic d) { return d ^ d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 14 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Equal() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 == d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 13 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void NotEqual() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 != d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 35 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void LessThan() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 < d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 20 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void GreaterThan() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 > d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 15 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void LessThanEquals() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 <= d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 21 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void GreaterThanEquals() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 >= d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void UnaryPlus() { string source = @" public class C { public dynamic M(dynamic d) { return +d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 29 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret } "); } [Fact] public void UnaryMinus() { string source = @" public class C { public dynamic M(dynamic d) { return -d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 28 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret }"); } [Fact] public void BitwiseComplement() { string source = @" public class C { public dynamic M(dynamic d) { return ~d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 82 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret } "); } [Fact] public void BooleanOperation_IsTrue() { string source = @" class C { public static int M() { dynamic dy = null; if (dy.Property_bool) { return 1; } else { return 0; } } }"; var verifier = CompileAndVerifyIL(source, "C.M", expectedUnoptimizedIL: @" { // Code size 169 (0xa9) .maxstack 10 .locals init (object V_0, //dy bool V_1, int V_2) -IL_0000: nop -IL_0001: ldnull IL_0002: stloc.0 -IL_0003: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0038 IL_000c: ldc.i4.0 IL_000d: ldc.i4.s 83 IL_000f: ldtoken ""C"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldc.i4.1 IL_001a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001f: dup IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0033: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004c: brfalse.s IL_0050 IL_004e: br.s IL_007f IL_0050: ldc.i4.0 IL_0051: ldstr ""Property_bool"" IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.1 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008e: ldloc.0 IL_008f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0099: stloc.1 ~IL_009a: ldloc.1 IL_009b: brfalse.s IL_00a2 -IL_009d: nop -IL_009e: ldc.i4.1 IL_009f: stloc.2 IL_00a0: br.s IL_00a7 -IL_00a2: nop -IL_00a3: ldc.i4.0 IL_00a4: stloc.2 IL_00a5: br.s IL_00a7 -IL_00a7: ldloc.2 IL_00a8: ret } ", expectedOptimizedIL: @" { // Code size 154 (0x9a) .maxstack 10 .locals init (object V_0) //dy IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_007a IL_004b: ldc.i4.0 IL_004c: ldstr ""Property_bool"" IL_0051: ldtoken ""C"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldc.i4.1 IL_005c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0061: dup IL_0062: ldc.i4.0 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0089: ldloc.0 IL_008a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008f: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: brfalse.s IL_0098 IL_0096: ldc.i4.1 IL_0097: ret IL_0098: ldc.i4.0 IL_0099: ret } "); } [Fact] public void BooleanOperation_Not() { string source = @" public class C { public static int M(dynamic d) { if (!d) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 149 (0x95) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0047: brtrue.s IL_0075 IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 34 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.1 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0070: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0075: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0084: ldarg.0 IL_0085: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008a: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008f: brfalse.s IL_0093 IL_0091: ldc.i4.1 IL_0092: ret IL_0093: ldc.i4.0 IL_0094: ret } "); } [Fact] public void BooleanOperation_And() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if (d1 && d2) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 236 (0xec) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0047: brtrue.s IL_0075 IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 84 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.1 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0070: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0075: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_007a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0084: ldarg.0 IL_0085: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008a: brtrue.s IL_00e0 IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0091: brtrue.s IL_00c8 IL_0093: ldc.i4.8 IL_0094: ldc.i4.2 IL_0095: ldtoken ""C"" IL_009a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009f: ldc.i4.2 IL_00a0: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a5: dup IL_00a6: ldc.i4.0 IL_00a7: ldc.i4.0 IL_00a8: ldnull IL_00a9: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ae: stelem.ref IL_00af: dup IL_00b0: ldc.i4.1 IL_00b1: ldc.i4.0 IL_00b2: ldnull IL_00b3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b8: stelem.ref IL_00b9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00be: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00cd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d7: ldarg.0 IL_00d8: ldarg.1 IL_00d9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00de: br.s IL_00e1 IL_00e0: ldarg.0 IL_00e1: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e6: brfalse.s IL_00ea IL_00e8: ldc.i4.1 IL_00e9: ret IL_00ea: ldc.i4.0 IL_00eb: ret }"); } [WorkItem(547676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547676")] [Fact] public void BooleanOperation_Bug547676() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if ((d1 == 1) && d2 && d2) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 480 (0x1e0) .maxstack 10 .locals init (object V_0, object V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0047: brtrue.s IL_007f IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 13 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.2 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: dup IL_0067: ldc.i4.1 IL_0068: ldc.i4.3 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0095: stloc.1 IL_0096: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_009b: brtrue.s IL_00c9 IL_009d: ldc.i4.0 IL_009e: ldc.i4.s 84 IL_00a0: ldtoken ""C"" IL_00a5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00aa: ldc.i4.1 IL_00ab: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b0: dup IL_00b1: ldc.i4.0 IL_00b2: ldc.i4.0 IL_00b3: ldnull IL_00b4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b9: stelem.ref IL_00ba: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bf: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00c9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00ce: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_00d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00d8: ldloc.1 IL_00d9: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00de: brtrue.s IL_0134 IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00e5: brtrue.s IL_011c IL_00e7: ldc.i4.8 IL_00e8: ldc.i4.2 IL_00e9: ldtoken ""C"" IL_00ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00f3: ldc.i4.2 IL_00f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00f9: dup IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.0 IL_00fc: ldnull IL_00fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0102: stelem.ref IL_0103: dup IL_0104: ldc.i4.1 IL_0105: ldc.i4.0 IL_0106: ldnull IL_0107: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010c: stelem.ref IL_010d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0112: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0117: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_011c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0121: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0126: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_012b: ldloc.1 IL_012c: ldarg.1 IL_012d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0132: br.s IL_0135 IL_0134: ldloc.1 IL_0135: stloc.0 IL_0136: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_013b: brtrue.s IL_0169 IL_013d: ldc.i4.0 IL_013e: ldc.i4.s 84 IL_0140: ldtoken ""C"" IL_0145: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_014a: ldc.i4.1 IL_014b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0150: dup IL_0151: ldc.i4.0 IL_0152: ldc.i4.0 IL_0153: ldnull IL_0154: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0159: stelem.ref IL_015a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_015f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0164: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_0169: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_016e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0173: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_0178: ldloc.0 IL_0179: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_017e: brtrue.s IL_01d4 IL_0180: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_0185: brtrue.s IL_01bc IL_0187: ldc.i4.8 IL_0188: ldc.i4.2 IL_0189: ldtoken ""C"" IL_018e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0193: ldc.i4.2 IL_0194: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0199: dup IL_019a: ldc.i4.0 IL_019b: ldc.i4.0 IL_019c: ldnull IL_019d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01a2: stelem.ref IL_01a3: dup IL_01a4: ldc.i4.1 IL_01a5: ldc.i4.0 IL_01a6: ldnull IL_01a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01ac: stelem.ref IL_01ad: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01b2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01b7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01c1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_01c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01cb: ldloc.0 IL_01cc: ldarg.1 IL_01cd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01d2: br.s IL_01d5 IL_01d4: ldloc.0 IL_01d5: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01da: brfalse.s IL_01de IL_01dc: ldc.i4.1 IL_01dd: ret IL_01de: ldc.i4.0 IL_01df: ret }"); } [Fact] public void BooleanOperation_Or_Dynamic_Dynamic() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if (d1 || d2) { return 1; } else { return 0; } } }"; // Dev11 emits less efficient code: // IsTrue(IsTrue(d1) ? d1 : Or(d1, d2)) // // Roslyn optimizes away the second dynamic call IsTrue on d1: // IsTrue(d1) || IsTrue(Or(d1, d2)) CompileAndVerifyIL(source, "C.M", @" { // Code size 237 (0xed) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldarg.0 IL_0043: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: brtrue IL_00e9 IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0052: brtrue.s IL_0080 IL_0054: ldc.i4.0 IL_0055: ldc.i4.s 83 IL_0057: ldtoken ""C"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldc.i4.1 IL_0062: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0067: dup IL_0068: ldc.i4.0 IL_0069: ldc.i4.0 IL_006a: ldnull IL_006b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0070: stelem.ref IL_0071: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0076: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0080: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0085: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0094: brtrue.s IL_00cc IL_0096: ldc.i4.8 IL_0097: ldc.i4.s 36 IL_0099: ldtoken ""C"" IL_009e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a3: ldc.i4.2 IL_00a4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a9: dup IL_00aa: ldc.i4.0 IL_00ab: ldc.i4.0 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.1 IL_00b5: ldc.i4.0 IL_00b6: ldnull IL_00b7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bc: stelem.ref IL_00bd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00cc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00db: ldarg.0 IL_00dc: ldarg.1 IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00e2: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e7: brfalse.s IL_00eb IL_00e9: ldc.i4.1 IL_00ea: ret IL_00eb: ldc.i4.0 IL_00ec: ret } "); } [Fact] public void BooleanOperation_Or_Static_Dynamic() { string source = @" public class C { public static int M(bool b, dynamic d) { if (b || d) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 166 (0xa6) .maxstack 10 IL_0000: ldarg.0 IL_0001: brtrue IL_00a2 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_000b: brtrue.s IL_0039 IL_000d: ldc.i4.0 IL_000e: ldc.i4.s 83 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.1 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.0 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0034: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_004d: brtrue.s IL_0085 IL_004f: ldc.i4.8 IL_0050: ldc.i4.s 36 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.2 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.1 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.0 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0080: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_008a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0094: ldarg.0 IL_0095: ldarg.1 IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_009b: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a0: brfalse.s IL_00a4 IL_00a2: ldc.i4.1 IL_00a3: ret IL_00a4: ldc.i4.0 IL_00a5: ret }"); } [Fact] public void BooleanOperation_Or_ConstantOperand_False() { string source = @" class C { int M() { dynamic d = null; return (false || d) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 162 (0xa2) .maxstack 10 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_0081 IL_004b: ldc.i4.8 IL_004c: ldc.i4.s 36 IL_004e: ldtoken ""C"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldc.i4.2 IL_0059: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005e: dup IL_005f: ldc.i4.0 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0090: ldc.i4.0 IL_0091: ldloc.0 IL_0092: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0097: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009c: brtrue.s IL_00a0 IL_009e: ldc.i4.2 IL_009f: ret IL_00a0: ldc.i4.1 IL_00a1: ret } "); } [Fact] public void BooleanOperation_Or_ConstantOperand_True() { string source = @" class C { int M() { dynamic d = null; return (true || d) ? 1 : 2; } } "; // Dev11 emits: // IsTrue(IsTrue(true) ? true : Or(true, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [Fact] public void BooleanOperation_Add_ConstantOperand_False() { string source = @" class C { int M() { dynamic d = null; return (false && d) ? 1 : 2; } } "; // Dev11: IsTrue(IsFalse(false) ? false : And(false, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } "); } [Fact] public void BooleanOperation_ConstantPropagation() { string source = @" class C { int M() { dynamic d = null; return (!(false && d) || d) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [Fact] public void BooleanOperation_ConstantPropagation2() { string source = @" class C { int M() { dynamic d = null; return ((dynamic)false) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } "); } [Fact] public void BooleanOperation_Add_ConstantOperand_True() { string source = @" class C { int M() { dynamic d = null; return (true && d) ? 1 : 2; } } "; // Dev11: IsTrue(IsFalse(true) ? true : And(true, d)) ? 1 : 2 // Roslyn: IsTrue(And(true, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 161 (0xa1) .maxstack 10 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_0080 IL_004b: ldc.i4.8 IL_004c: ldc.i4.2 IL_004d: ldtoken ""C"" IL_0052: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0057: ldc.i4.2 IL_0058: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005d: dup IL_005e: ldc.i4.0 IL_005f: ldc.i4.3 IL_0060: ldnull IL_0061: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0066: stelem.ref IL_0067: dup IL_0068: ldc.i4.1 IL_0069: ldc.i4.0 IL_006a: ldnull IL_006b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0070: stelem.ref IL_0071: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0076: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0080: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0085: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_008f: ldc.i4.1 IL_0090: ldloc.0 IL_0091: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0096: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009b: brtrue.s IL_009f IL_009d: ldc.i4.2 IL_009e: ret IL_009f: ldc.i4.1 IL_00a0: ret } "); } [Fact] public void BooleanOperation_Or_BoxedOperand() { string source = @" class C { bool b = false; dynamic M() { dynamic d = null; return b || d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 8 .locals init (object V_0, //d bool V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldfld ""bool C.b"" IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: brtrue.s IL_0060 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0049 IL_0013: ldc.i4.8 IL_0014: ldc.i4.s 36 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0058: ldloc.1 IL_0059: ldloc.0 IL_005a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_005f: ret IL_0060: ldloc.1 IL_0061: box ""bool"" IL_0066: ret } "); } [Fact] public void BooleanOperation_And_BoxedOperand() { string source = @" class C { bool b = false; dynamic M() { dynamic d = null; return b && d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 8 .locals init (object V_0, //d bool V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldfld ""bool C.b"" IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: brfalse.s IL_005f IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0048 IL_0013: ldc.i4.8 IL_0014: ldc.i4.2 IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0057: ldloc.1 IL_0058: ldloc.0 IL_0059: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_005e: ret IL_005f: ldloc.1 IL_0060: box ""bool"" IL_0065: ret } "); } [Fact] public void BooleanOperation_Or_UserDefinedTrue_Dynamic() { string source = @" class B { public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b || d) { return 1; } return 2; } } "; // Dev11: IsTrue(B.op_True(b) ? b : Or(b, d)) ? 1 : 2 // Roslyn: B.op_True(b) || IsTrue(Or(b,d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 10 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool B.op_True(B)"" IL_000d: brtrue IL_00ae IL_0012: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0017: brtrue.s IL_0045 IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 83 IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.1 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0059: brtrue.s IL_0091 IL_005b: ldc.i4.8 IL_005c: ldc.i4.s 36 IL_005e: ldtoken ""C"" IL_0063: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0068: ldc.i4.2 IL_0069: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006e: dup IL_006f: ldc.i4.0 IL_0070: ldc.i4.1 IL_0071: ldnull IL_0072: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0077: stelem.ref IL_0078: dup IL_0079: ldc.i4.1 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_00a0: ldloc.0 IL_00a1: ldarg.1 IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ac: brfalse.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret } "); } /// <summary> /// Implicit conversion has precedence over operator true/false. /// </summary> [Fact] public void BooleanOperation_Or_UserDefinedImplicitConversion_Dynamic() { string source = @" class B { public static implicit operator bool(B t) { return true; } public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b || d) { return 1; } return 2; } } "; // Dev11: IsTrue(B.op_Implicit(b) ? b : Or(b, d)) ? 1 : 2 // Roslyn: B.op_Implicit(b) || IsTrue(Or(b,d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 10 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool B.op_Implicit(B)"" IL_000d: brtrue IL_00ae IL_0012: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0017: brtrue.s IL_0045 IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 83 IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.1 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0059: brtrue.s IL_0091 IL_005b: ldc.i4.8 IL_005c: ldc.i4.s 36 IL_005e: ldtoken ""C"" IL_0063: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0068: ldc.i4.2 IL_0069: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006e: dup IL_006f: ldc.i4.0 IL_0070: ldc.i4.1 IL_0071: ldnull IL_0072: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0077: stelem.ref IL_0078: dup IL_0079: ldc.i4.1 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_00a0: ldloc.0 IL_00a1: ldarg.1 IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ac: brfalse.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret }"); } [Fact] public void BooleanOperation_And_UserDefinedTrue_Dynamic() { string source = @" class B { public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b && d) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 177 (0xb1) .maxstack 10 .locals init (B V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0042: ldarg.0 IL_0043: ldfld ""B C.b"" IL_0048: stloc.0 IL_0049: ldloc.0 IL_004a: call ""bool B.op_False(B)"" IL_004f: brtrue.s IL_00a5 IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0056: brtrue.s IL_008d IL_0058: ldc.i4.8 IL_0059: ldc.i4.2 IL_005a: ldtoken ""C"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: ldc.i4.2 IL_0065: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006a: dup IL_006b: ldc.i4.0 IL_006c: ldc.i4.1 IL_006d: ldnull IL_006e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0073: stelem.ref IL_0074: dup IL_0075: ldc.i4.1 IL_0076: ldc.i4.0 IL_0077: ldnull IL_0078: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007d: stelem.ref IL_007e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0083: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0088: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_008d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0092: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0097: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_009c: ldloc.0 IL_009d: ldarg.1 IL_009e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a3: br.s IL_00a6 IL_00a5: ldloc.0 IL_00a6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ab: brfalse.s IL_00af IL_00ad: ldc.i4.1 IL_00ae: ret IL_00af: ldc.i4.2 IL_00b0: ret } "); } /// <summary> /// Implicit conversion has precedence over operator true/false. /// </summary> [Fact] public void BooleanOperation_And_UserDefinedImplicitConversion_Dynamic() { string source = @" class B { public static implicit operator bool(B t) { return true; } public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b && d) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 177 (0xb1) .maxstack 10 .locals init (B V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0042: ldarg.0 IL_0043: ldfld ""B C.b"" IL_0048: stloc.0 IL_0049: ldloc.0 IL_004a: call ""bool B.op_Implicit(B)"" IL_004f: brfalse.s IL_00a5 IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0056: brtrue.s IL_008d IL_0058: ldc.i4.8 IL_0059: ldc.i4.2 IL_005a: ldtoken ""C"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: ldc.i4.2 IL_0065: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006a: dup IL_006b: ldc.i4.0 IL_006c: ldc.i4.1 IL_006d: ldnull IL_006e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0073: stelem.ref IL_0074: dup IL_0075: ldc.i4.1 IL_0076: ldc.i4.0 IL_0077: ldnull IL_0078: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007d: stelem.ref IL_007e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0083: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0088: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_008d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0092: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0097: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_009c: ldloc.0 IL_009d: ldarg.1 IL_009e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a3: br.s IL_00a6 IL_00a5: ldloc.0 IL_00a6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ab: brfalse.s IL_00af IL_00ad: ldc.i4.1 IL_00ae: ret IL_00af: ldc.i4.2 IL_00b0: ret } "); } private const string StructWithUserDefinedBooleanOperators = @" struct S { private int num; private string str; public S(int num, char chr) { this.num = num; this.str = chr.ToString(); } public S(int num, string str) { this.num = num; this.str = str; } public static S operator & (S x, S y) { return new S(x.num & y.num, '(' + x.str + '&' + y.str + ')'); } public static S operator | (S x, S y) { return new S(x.num | y.num, '(' + x.str + '|' + y.str + ')'); } public static bool operator true(S s) { return s.num != 0; } public static bool operator false(S s) { return s.num == 0; } public override string ToString() { return this.num.ToString() + ':' + this.str; } } "; [Fact] public void BooleanOperation_NestedOperators1() { // Analogue to OperatorTests.TestUserDefinedLogicalOperators1. string source = @" using System; class C { static void Main() { dynamic f = new S(0, 'f'); dynamic t = new S(1, 't'); Console.WriteLine((f && f) && f); Console.WriteLine((f && f) && t); Console.WriteLine((f && t) && f); Console.WriteLine((f && t) && t); Console.WriteLine((t && f) && f); Console.WriteLine((t && f) && t); Console.WriteLine((t && t) && f); Console.WriteLine((t && t) && t); Console.WriteLine('-'); Console.WriteLine((f && f) || f); Console.WriteLine((f && f) || t); Console.WriteLine((f && t) || f); Console.WriteLine((f && t) || t); Console.WriteLine((t && f) || f); Console.WriteLine((t && f) || t); Console.WriteLine((t && t) || f); Console.WriteLine((t && t) || t); Console.WriteLine('-'); Console.WriteLine((f || f) && f); Console.WriteLine((f || f) && t); Console.WriteLine((f || t) && f); Console.WriteLine((f || t) && t); Console.WriteLine((t || f) && f); Console.WriteLine((t || f) && t); Console.WriteLine((t || t) && f); Console.WriteLine((t || t) && t); Console.WriteLine('-'); Console.WriteLine((f || f) || f); Console.WriteLine((f || f) || t); Console.WriteLine((f || t) || f); Console.WriteLine((f || t) || t); Console.WriteLine((t || f) || f); Console.WriteLine((t || f) || t); Console.WriteLine((t || t) || f); Console.WriteLine((t || t) || t); Console.WriteLine('-'); Console.WriteLine(f && (f && f)); Console.WriteLine(f && (f && t)); Console.WriteLine(f && (t && f)); Console.WriteLine(f && (t && t)); Console.WriteLine(t && (f && f)); Console.WriteLine(t && (f && t)); Console.WriteLine(t && (t && f)); Console.WriteLine(t && (t && t)); Console.WriteLine('-'); Console.WriteLine(f && (f || f)); Console.WriteLine(f && (f || t)); Console.WriteLine(f && (t || f)); Console.WriteLine(f && (t || t)); Console.WriteLine(t && (f || f)); Console.WriteLine(t && (f || t)); Console.WriteLine(t && (t || f)); Console.WriteLine(t && (t || t)); Console.WriteLine('-'); Console.WriteLine(f || (f && f)); Console.WriteLine(f || (f && t)); Console.WriteLine(f || (t && f)); Console.WriteLine(f || (t && t)); Console.WriteLine(t || (f && f)); Console.WriteLine(t || (f && t)); Console.WriteLine(t || (t && f)); Console.WriteLine(t || (t && t)); Console.WriteLine('-'); Console.WriteLine(f || (f || f)); Console.WriteLine(f || (f || t)); Console.WriteLine(f || (t || f)); Console.WriteLine(f || (t || t)); Console.WriteLine(t || (f || f)); Console.WriteLine(t || (f || t)); Console.WriteLine(t || (t || f)); Console.WriteLine(t || (t || t)); } } " + StructWithUserDefinedBooleanOperators; string output = @"0:f 0:f 0:f 0:f 0:(t&f) 0:(t&f) 0:((t&t)&f) 1:((t&t)&t) - 0:(f|f) 1:(f|t) 0:(f|f) 1:(f|t) 0:((t&f)|f) 1:((t&f)|t) 1:(t&t) 1:(t&t) - 0:(f|f) 0:(f|f) 0:((f|t)&f) 1:((f|t)&t) 0:(t&f) 1:(t&t) 0:(t&f) 1:(t&t) - 0:((f|f)|f) 1:((f|f)|t) 1:(f|t) 1:(f|t) 1:t 1:t 1:t 1:t - 0:f 0:f 0:f 0:f 0:(t&f) 0:(t&f) 0:(t&(t&f)) 1:(t&(t&t)) - 0:f 0:f 0:f 0:f 0:(t&(f|f)) 1:(t&(f|t)) 1:(t&t) 1:(t&t) - 0:(f|f) 0:(f|f) 0:(f|(t&f)) 1:(f|(t&t)) 1:t 1:t 1:t 1:t - 0:(f|(f|f)) 1:(f|(f|t)) 1:(f|t) 1:(f|t) 1:t 1:t 1:t 1:t"; CompileAndVerifyWithCSharp(source: source, expectedOutput: output); } [Fact] public void BooleanOperation_NestedOperators2() { // Analogue to OperatorTests.TestUserDefinedLogicalOperators2. string source = @" using System; class C { static void Main() { dynamic f = new S(0, 'f'); dynamic t = new S(1, 't'); Console.Write((f && f) && f ? 1 : 0); Console.Write((f && f) && t ? 1 : 0); Console.Write((f && t) && f ? 1 : 0); Console.Write((f && t) && t ? 1 : 0); Console.Write((t && f) && f ? 1 : 0); Console.Write((t && f) && t ? 1 : 0); Console.Write((t && t) && f ? 1 : 0); Console.Write((t && t) && t ? 1 : 0); Console.WriteLine('-'); Console.Write((f && f) || f ? 1 : 0); Console.Write((f && f) || t ? 1 : 0); Console.Write((f && t) || f ? 1 : 0); Console.Write((f && t) || t ? 1 : 0); Console.Write((t && f) || f ? 1 : 0); Console.Write((t && f) || t ? 1 : 0); Console.Write((t && t) || f ? 1 : 0); Console.Write((t && t) || t ? 1 : 0); Console.WriteLine('-'); Console.Write((f || f) && f ? 1 : 0); Console.Write((f || f) && t ? 1 : 0); Console.Write((f || t) && f ? 1 : 0); Console.Write((f || t) && t ? 1 : 0); Console.Write((t || f) && f ? 1 : 0); Console.Write((t || f) && t ? 1 : 0); Console.Write((t || t) && f ? 1 : 0); Console.Write((t || t) && t ? 1 : 0); Console.WriteLine('-'); Console.Write((f || f) || f ? 1 : 0); Console.Write((f || f) || t ? 1 : 0); Console.Write((f || t) || f ? 1 : 0); Console.Write((f || t) || t ? 1 : 0); Console.Write((t || f) || f ? 1 : 0); Console.Write((t || f) || t ? 1 : 0); Console.Write((t || t) || f ? 1 : 0); Console.Write((t || t) || t ? 1 : 0); Console.WriteLine('-'); Console.Write(f && (f && f) ? 1 : 0); Console.Write(f && (f && t) ? 1 : 0); Console.Write(f && (t && f) ? 1 : 0); Console.Write(f && (t && t) ? 1 : 0); Console.Write(t && (f && f) ? 1 : 0); Console.Write(t && (f && t) ? 1 : 0); Console.Write(t && (t && f) ? 1 : 0); Console.Write(t && (t && t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f && (f || f) ? 1 : 0); Console.Write(f && (f || t) ? 1 : 0); Console.Write(f && (t || f) ? 1 : 0); Console.Write(f && (t || t) ? 1 : 0); Console.Write(t && (f || f) ? 1 : 0); Console.Write(t && (f || t) ? 1 : 0); Console.Write(t && (t || f) ? 1 : 0); Console.Write(t && (t || t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f || (f && f) ? 1 : 0); Console.Write(f || (f && t) ? 1 : 0); Console.Write(f || (t && f) ? 1 : 0); Console.Write(f || (t && t) ? 1 : 0); Console.Write(t || (f && f) ? 1 : 0); Console.Write(t || (f && t) ? 1 : 0); Console.Write(t || (t && f) ? 1 : 0); Console.Write(t || (t && t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f || (f || f) ? 1 : 0); Console.Write(f || (f || t) ? 1 : 0); Console.Write(f || (t || f) ? 1 : 0); Console.Write(f || (t || t) ? 1 : 0); Console.Write(t || (f || f) ? 1 : 0); Console.Write(t || (f || t) ? 1 : 0); Console.Write(t || (t || f) ? 1 : 0); Console.Write(t || (t || t) ? 1 : 0); } } " + StructWithUserDefinedBooleanOperators; string output = @" 00000001- 01010111- 00010101- 01111111- 00000001- 00000111- 00011111- 01111111"; CompileAndVerifyWithCSharp(source: source, expectedOutput: output); } [Fact] public void BooleanOperation_EvaluationOrder() { string source = @" public class C { public static dynamic f(ref dynamic d) { d = false; return d; } public static void Main() { dynamic d = true; if (d || f(ref d)) { return; } else { throw null; } } } "; CompileAndVerifyWithCSharp(source, expectedOutput: ""); } [Fact] public void Multiplication_CompoundAssignment() { string source = @" public class C { public dynamic M(dynamic d) { return d *= d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Multiplication_CompoundAssignment_Checked() { string source = @" public class C { public dynamic M(dynamic d) { return checked(d *= d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Multiplication_CompoundAssignment_DiscardResult() { string source = @" public class C { public void M(dynamic d) { d *= d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 86 (0x56) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: starg.s V_1 IL_0055: ret } "); } [Fact] public void Addition_CompoundAssignment() { string source = @" public class C { public dynamic M(dynamic d, dynamic v) { return d += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 63 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Addition_EventHandler_SimpleConversion() { string source = @" public class C { event System.Action e; dynamic v; public void M() { e += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""System.Action"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_003b: ldarg.0 IL_003c: ldfld ""dynamic C.v"" IL_0041: callvirt ""System.Action System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: call ""void C.e.add"" IL_004b: ret }"); } [Fact] public void PostIncrement() { string source = @" public class C { public dynamic M(dynamic d) { return d++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 8 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 54 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0044: ldloc.0 IL_0045: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004a: starg.s V_1 IL_004c: ldloc.0 IL_004d: ret }"); } [Fact] public void PostDecrement() { string source = @" public class C { public dynamic M(dynamic d) { return d--; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 8 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 49 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0044: ldloc.0 IL_0045: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004a: starg.s V_1 IL_004c: ldloc.0 IL_004d: ret }"); } [Fact] public void PreIncrement() { string source = @" public class C { public dynamic M(dynamic d) { return ++d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 54 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: dup IL_0049: starg.s V_1 IL_004b: ret }"); } [Fact] public void PreDecrement() { string source = @" public class C { public dynamic M(dynamic d) { return --d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 49 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: dup IL_0049: starg.s V_1 IL_004b: ret } "); } [Fact] public void PostIncrement_DynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static void M() { d[0]++; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 10 .locals init (object V_0) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: ldelem.ref IL_0008: stloc.0 IL_0009: ldc.i4.0 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_000f: brtrue.s IL_003d IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 54 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004c: ldloc.0 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0052: stelem.ref IL_0053: ret }"); } [Fact] public void PreIncrement_DynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static void M() { ++d[0]; } } "; // TODO (tomat): IL_0050 ... IL_0053 and V_1 could be optimized away CompileAndVerifyIL(source, "C.M", @" { // Code size 86 (0x56) .maxstack 8 .locals init (object[] V_0, object V_1) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_000b: brtrue.s IL_0039 IL_000d: ldc.i4.0 IL_000e: ldc.i4.s 54 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.1 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.0 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0034: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_003e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0048: ldloc.0 IL_0049: ldc.i4.0 IL_004a: ldelem.ref IL_004b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldc.i4.0 IL_0053: ldloc.1 IL_0054: stelem.ref IL_0055: ret }"); } [Fact] public void PreIncrement_DynamicMemberAccess() { string source = @" class C { dynamic d = null; dynamic M() { return ++d.P; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 243 (0xf3) .maxstack 10 .locals init (object V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_003a IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 54 IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.1 IL_001c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0021: dup IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002a: stelem.ref IL_002b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0030: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0035: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004e: brtrue.s IL_007f IL_0050: ldc.i4.0 IL_0051: ldstr ""P"" IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.1 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_008e: ldloc.0 IL_008f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0099: stloc.1 IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_009f: brtrue.s IL_00da IL_00a1: ldc.i4.0 IL_00a2: ldstr ""P"" IL_00a7: ldtoken ""C"" IL_00ac: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b1: ldc.i4.2 IL_00b2: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b7: dup IL_00b8: ldc.i4.0 IL_00b9: ldc.i4.0 IL_00ba: ldnull IL_00bb: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c0: stelem.ref IL_00c1: dup IL_00c2: ldc.i4.1 IL_00c3: ldc.i4.0 IL_00c4: ldnull IL_00c5: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ca: stelem.ref IL_00cb: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d0: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d5: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00df: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00e4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00e9: ldloc.0 IL_00ea: ldloc.1 IL_00eb: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f0: pop IL_00f1: ldloc.1 IL_00f2: ret } "); } [Fact] public void PostIncrement_DynamicMemberAccess() { string source = @" class C { dynamic d = null; dynamic M() { return d.P++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 243 (0xf3) .maxstack 11 .locals init (object V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_003d IL_000e: ldc.i4.0 IL_000f: ldstr ""P"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_004c: ldloc.0 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0052: stloc.1 IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0058: brtrue.s IL_0093 IL_005a: ldc.i4.0 IL_005b: ldstr ""P"" IL_0060: ldtoken ""C"" IL_0065: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006a: ldc.i4.2 IL_006b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0070: dup IL_0071: ldc.i4.0 IL_0072: ldc.i4.0 IL_0073: ldnull IL_0074: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0079: stelem.ref IL_007a: dup IL_007b: ldc.i4.1 IL_007c: ldc.i4.0 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0089: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0093: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0098: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00a2: ldloc.0 IL_00a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00a8: brtrue.s IL_00d6 IL_00aa: ldc.i4.0 IL_00ab: ldc.i4.s 54 IL_00ad: ldtoken ""C"" IL_00b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b7: ldc.i4.1 IL_00b8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bd: dup IL_00be: ldc.i4.0 IL_00bf: ldc.i4.0 IL_00c0: ldnull IL_00c1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c6: stelem.ref IL_00c7: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cc: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d1: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00db: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00e5: ldloc.1 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00eb: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f0: pop IL_00f1: ldloc.1 IL_00f2: ret } "); } [Fact] public void PreIncrement_DynamicIndexerAccess() { string source = @" class C { dynamic d = null; int F() { return 0; } dynamic M() { return ++d[F()]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 262 (0x106) .maxstack 9 .locals init (object V_0, int V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: call ""int C.F()"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0013: brtrue.s IL_0041 IL_0015: ldc.i4.0 IL_0016: ldc.i4.s 54 IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.1 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0037: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0046: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_0055: brtrue.s IL_008b IL_0057: ldc.i4.0 IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.2 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.1 IL_0074: ldc.i4.1 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_009a: ldloc.0 IL_009b: ldloc.1 IL_009c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a6: stloc.2 IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00ac: brtrue.s IL_00ec IL_00ae: ldc.i4.0 IL_00af: ldtoken ""C"" IL_00b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b9: ldc.i4.3 IL_00ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bf: dup IL_00c0: ldc.i4.0 IL_00c1: ldc.i4.0 IL_00c2: ldnull IL_00c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c8: stelem.ref IL_00c9: dup IL_00ca: ldc.i4.1 IL_00cb: ldc.i4.1 IL_00cc: ldnull IL_00cd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d2: stelem.ref IL_00d3: dup IL_00d4: ldc.i4.2 IL_00d5: ldc.i4.0 IL_00d6: ldnull IL_00d7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00dc: stelem.ref IL_00dd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00e2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00f1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_00f6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00fb: ldloc.0 IL_00fc: ldloc.1 IL_00fd: ldloc.2 IL_00fe: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_0103: pop IL_0104: ldloc.2 IL_0105: ret }"); } [Fact] public void PostIncrement_DynamicIndexerAccess() { string source = @" class C { dynamic d = null; int F() { return 0; } dynamic M() { return d[F()]++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 262 (0x106) .maxstack 12 .locals init (object V_0, int V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: call ""int C.F()"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0013: brtrue.s IL_0049 IL_0015: ldc.i4.0 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.1 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0058: ldloc.0 IL_0059: ldloc.1 IL_005a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_005f: stloc.2 IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_0065: brtrue.s IL_00a5 IL_0067: ldc.i4.0 IL_0068: ldtoken ""C"" IL_006d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0072: ldc.i4.3 IL_0073: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0078: dup IL_0079: ldc.i4.0 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: dup IL_0083: ldc.i4.1 IL_0084: ldc.i4.1 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.2 IL_008e: ldc.i4.0 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00aa: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_00af: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00b4: ldloc.0 IL_00b5: ldloc.1 IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00bb: brtrue.s IL_00e9 IL_00bd: ldc.i4.0 IL_00be: ldc.i4.s 54 IL_00c0: ldtoken ""C"" IL_00c5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ca: ldc.i4.1 IL_00cb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d0: dup IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldnull IL_00d4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d9: stelem.ref IL_00da: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00df: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00e9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ee: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00f8: ldloc.2 IL_00f9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00fe: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_0103: pop IL_0104: ldloc.2 IL_0105: ret }"); } [Fact] public void NullCoalescing() { string source = @" class C { dynamic d = null; object o = null; void M() { var x = d ?? o; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: brtrue.s IL_000f IL_0008: ldarg.0 IL_0009: ldfld ""object C.o"" IL_000e: pop IL_000f: ret } "); } #endregion #region Invoke, InvokeMember, InvokeConstructor [Fact] public void InvokeMember_Dynamic() { string source = @" public class C { public dynamic M(dynamic d) { return d.m(null, this, d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.1 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.1 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c.F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.1 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.2 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static_SimpleName() { string source = @" public class C { public dynamic M(C c, dynamic d) { return F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.2 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.0 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.2 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static_ResultDiscarded() { string source = @" public class C { public void M(C c, dynamic d) { F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 114 (0x72) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0059 IL_0007: ldc.i4 0x102 IL_000c: ldstr ""F"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.4 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.2 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.1 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.0 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004f: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0054: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_005e: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>>.Target"" IL_0063: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0068: ldarg.0 IL_0069: ldnull IL_006a: ldarg.0 IL_006b: ldarg.2 IL_006c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_0071: ret } "); } [Fact] [WorkItem(622532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622532")] public void InvokeMember_Static_Outer() { string source = @" using System; public class A { public static void M(int x) { } public class B { public void F() { dynamic d = null; M(d); } } }"; // Dev11 passes "this" to the site, which is wrong. CompileAndVerifyIL(source, "A.B.F", @" { // Code size 104 (0x68) .maxstack 9 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0048 IL_0009: ldc.i4 0x100 IL_000e: ldstr ""M"" IL_0013: ldnull IL_0014: ldtoken ""A.B"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.s 33 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_004d: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0057: ldtoken ""A"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldloc.0 IL_0062: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: ret } "); } [Fact] [WorkItem(622532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622532")] public void InvokeMember_Static_Outer_AmbiguousAtRuntime() { string source = @" using System; public class A { public static void M(A x) { } public void M(string x) { } public class B { public void F() { dynamic d = null; M(d); } } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { new A.B().F(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; // Dev11 passes "this" to the site, which is wrong. CompileAndVerifyIL(source, "A.B.F", @" { // Code size 104 (0x68) .maxstack 9 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0048 IL_0009: ldc.i4 0x100 IL_000e: ldstr ""M"" IL_0013: ldnull IL_0014: ldtoken ""A.B"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.s 33 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_004d: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0057: ldtoken ""A"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldloc.0 IL_0062: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: ret }"); CompileAndVerifyWithCSharp(source, expectedOutput: "The call is ambiguous between the following methods or properties: 'A.M(A)' and 'A.M(string)'"); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_StaticProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static Color Color { get; set; } public static void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 286 (0x11e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: call ""Color C.Color.get"" IL_0059: ldarg.0 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0064: brtrue.s IL_00a4 IL_0066: ldc.i4 0x100 IL_006b: ldstr ""M2"" IL_0070: ldnull IL_0071: ldtoken ""C"" IL_0076: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007b: ldc.i4.2 IL_007c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0081: dup IL_0082: ldc.i4.0 IL_0083: ldc.i4.1 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.1 IL_008d: ldc.i4.0 IL_008e: ldnull IL_008f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0094: stelem.ref IL_0095: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a9: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b3: call ""Color C.Color.get"" IL_00b8: ldarg.0 IL_00b9: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c3: brtrue.s IL_0103 IL_00c5: ldc.i4 0x100 IL_00ca: ldstr ""M3"" IL_00cf: ldnull IL_00d0: ldtoken ""C"" IL_00d5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00da: ldc.i4.2 IL_00db: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e0: dup IL_00e1: ldc.i4.0 IL_00e2: ldc.i4.1 IL_00e3: ldnull IL_00e4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e9: stelem.ref IL_00ea: dup IL_00eb: ldc.i4.1 IL_00ec: ldc.i4.0 IL_00ed: ldnull IL_00ee: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f3: stelem.ref IL_00f4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f9: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fe: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0103: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0108: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0112: call ""Color C.Color.get"" IL_0117: ldarg.0 IL_0118: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_011d: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_InstanceProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public Color Color { get; set; } public static void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); // Dev11 crashes on this one } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 304 (0x130) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0055: ldtoken ""Color"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_006a: brtrue.s IL_00ab IL_006c: ldc.i4 0x100 IL_0071: ldstr ""M2"" IL_0076: ldnull IL_0077: ldtoken ""C"" IL_007c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0081: ldc.i4.2 IL_0082: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0087: dup IL_0088: ldc.i4.0 IL_0089: ldc.i4.s 33 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.1 IL_0094: ldc.i4.0 IL_0095: ldnull IL_0096: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009b: stelem.ref IL_009c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00b0: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_00b5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00ba: ldtoken ""Color"" IL_00bf: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c4: ldarg.0 IL_00c5: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_00ca: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_00cf: brtrue.s IL_0110 IL_00d1: ldc.i4 0x100 IL_00d6: ldstr ""M3"" IL_00db: ldnull IL_00dc: ldtoken ""C"" IL_00e1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00e6: ldc.i4.2 IL_00e7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00ec: dup IL_00ed: ldc.i4.0 IL_00ee: ldc.i4.s 33 IL_00f0: ldnull IL_00f1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f6: stelem.ref IL_00f7: dup IL_00f8: ldc.i4.1 IL_00f9: ldc.i4.0 IL_00fa: ldnull IL_00fb: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0100: stelem.ref IL_0101: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0106: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_010b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_0110: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_0115: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_011a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_011f: ldtoken ""Color"" IL_0124: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0129: ldarg.0 IL_012a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_012f: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_Parameter() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static void F(Color Color, dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); // Dev11 crashes on this one } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 274 (0x112) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.0 IL_0055: ldarg.1 IL_0056: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_0060: brtrue.s IL_00a0 IL_0062: ldc.i4 0x100 IL_0067: ldstr ""M2"" IL_006c: ldnull IL_006d: ldtoken ""C"" IL_0072: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0077: ldc.i4.2 IL_0078: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_007d: dup IL_007e: ldc.i4.0 IL_007f: ldc.i4.1 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.1 IL_0089: ldc.i4.0 IL_008a: ldnull IL_008b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0090: stelem.ref IL_0091: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0096: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a5: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00af: ldarg.0 IL_00b0: ldarg.1 IL_00b1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00bb: brtrue.s IL_00fb IL_00bd: ldc.i4 0x100 IL_00c2: ldstr ""M3"" IL_00c7: ldnull IL_00c8: ldtoken ""C"" IL_00cd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00d2: ldc.i4.2 IL_00d3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d8: dup IL_00d9: ldc.i4.0 IL_00da: ldc.i4.1 IL_00db: ldnull IL_00dc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e1: stelem.ref IL_00e2: dup IL_00e3: ldc.i4.1 IL_00e4: ldc.i4.0 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_0100: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_010a: ldarg.0 IL_010b: ldarg.1 IL_010c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0111: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_StaticProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static Color Color { get; set; } public void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 286 (0x11e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: call ""Color C.Color.get"" IL_0059: ldarg.1 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0064: brtrue.s IL_00a4 IL_0066: ldc.i4 0x100 IL_006b: ldstr ""M2"" IL_0070: ldnull IL_0071: ldtoken ""C"" IL_0076: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007b: ldc.i4.2 IL_007c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0081: dup IL_0082: ldc.i4.0 IL_0083: ldc.i4.1 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.1 IL_008d: ldc.i4.0 IL_008e: ldnull IL_008f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0094: stelem.ref IL_0095: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a9: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b3: call ""Color C.Color.get"" IL_00b8: ldarg.1 IL_00b9: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c3: brtrue.s IL_0103 IL_00c5: ldc.i4 0x100 IL_00ca: ldstr ""M3"" IL_00cf: ldnull IL_00d0: ldtoken ""C"" IL_00d5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00da: ldc.i4.2 IL_00db: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e0: dup IL_00e1: ldc.i4.0 IL_00e2: ldc.i4.1 IL_00e3: ldnull IL_00e4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e9: stelem.ref IL_00ea: dup IL_00eb: ldc.i4.1 IL_00ec: ldc.i4.0 IL_00ed: ldnull IL_00ee: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f3: stelem.ref IL_00f4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f9: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fe: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0103: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0108: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0112: call ""Color C.Color.get"" IL_0117: ldarg.1 IL_0118: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_011d: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_Parameter() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public void F(Color Color, dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 274 (0x112) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.1 IL_0055: ldarg.2 IL_0056: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_0060: brtrue.s IL_00a0 IL_0062: ldc.i4 0x100 IL_0067: ldstr ""M2"" IL_006c: ldnull IL_006d: ldtoken ""C"" IL_0072: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0077: ldc.i4.2 IL_0078: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_007d: dup IL_007e: ldc.i4.0 IL_007f: ldc.i4.1 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.1 IL_0089: ldc.i4.0 IL_008a: ldnull IL_008b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0090: stelem.ref IL_0091: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0096: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a5: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00af: ldarg.1 IL_00b0: ldarg.2 IL_00b1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00bb: brtrue.s IL_00fb IL_00bd: ldc.i4 0x100 IL_00c2: ldstr ""M3"" IL_00c7: ldnull IL_00c8: ldtoken ""C"" IL_00cd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00d2: ldc.i4.2 IL_00d3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d8: dup IL_00d9: ldc.i4.0 IL_00da: ldc.i4.1 IL_00db: ldnull IL_00dc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e1: stelem.ref IL_00e2: dup IL_00e3: ldc.i4.1 IL_00e4: ldc.i4.0 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_0100: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_010a: ldarg.1 IL_010b: ldarg.2 IL_010c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0111: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_InstanceProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public Color Color { get; set; } public void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 289 (0x121) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: ldarg.0 IL_0055: call ""Color C.Color.get"" IL_005a: ldarg.1 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0065: brtrue.s IL_00a5 IL_0067: ldc.i4 0x100 IL_006c: ldstr ""M2"" IL_0071: ldnull IL_0072: ldtoken ""C"" IL_0077: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007c: ldc.i4.2 IL_007d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0082: dup IL_0083: ldc.i4.0 IL_0084: ldc.i4.1 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.1 IL_008e: ldc.i4.0 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00aa: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00af: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b4: ldarg.0 IL_00b5: call ""Color C.Color.get"" IL_00ba: ldarg.1 IL_00bb: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00c0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c5: brtrue.s IL_0105 IL_00c7: ldc.i4 0x100 IL_00cc: ldstr ""M3"" IL_00d1: ldnull IL_00d2: ldtoken ""C"" IL_00d7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00dc: ldc.i4.2 IL_00dd: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e2: dup IL_00e3: ldc.i4.0 IL_00e4: ldc.i4.1 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: dup IL_00ed: ldc.i4.1 IL_00ee: ldc.i4.0 IL_00ef: ldnull IL_00f0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f5: stelem.ref IL_00f6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00fb: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0100: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_010a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0114: ldarg.0 IL_0115: call ""Color C.Color.get"" IL_011a: ldarg.1 IL_011b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0120: ret }"); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InFieldInitializer() { string source = @" public class Color { public int F(int a) { return 1; } } public class C { Color Color; dynamic x = Color.F((dynamic)1); } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 115 (0x73) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0006: brtrue.s IL_0043 IL_0008: ldc.i4.0 IL_0009: ldstr ""F"" IL_000e: ldnull IL_000f: ldtoken ""C"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldc.i4.2 IL_001a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001f: dup IL_0020: ldc.i4.0 IL_0021: ldc.i4.s 33 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: dup IL_002b: ldc.i4.1 IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0039: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0048: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Target"" IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0052: ldtoken ""Color"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.1 IL_005d: box ""int"" IL_0062: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: stfld ""dynamic C.x"" IL_006c: ldarg.0 IL_006d: call ""object..ctor()"" IL_0072: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InScriptVariableInitializer() { var sourceLib = @" public class Color { public int F(int a) { return 1; } } "; var lib = CreateCompilation(sourceLib); string sourceScript = @" Color Color; dynamic x = Color.F((dynamic)1); "; var script = CreateCompilationWithMscorlib45( new[] { Parse(sourceScript, options: TestOptions.Script) }, new[] { new CSharpCompilationReference(lib), SystemCoreRef, CSharpRef }); var verifier = CompileAndVerify(script); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"{ // Code size 158 (0x9e) .maxstack 10 .locals init (Script V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""Script Script.<<Initialize>>d__0.<>4__this"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_000d: brtrue.s IL_0049 IL_000f: ldc.i4.0 IL_0010: ldstr ""F"" IL_0015: ldnull IL_0016: ldtoken ""Script"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_0058: ldloc.0 IL_0059: ldfld ""Color Script.Color"" IL_005e: ldc.i4.1 IL_005f: box ""int"" IL_0064: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0069: stfld ""dynamic Script.x"" IL_006e: ldnull IL_006f: stloc.1 IL_0070: leave.s IL_0089 } catch System.Exception { IL_0072: stloc.2 IL_0073: ldarg.0 IL_0074: ldc.i4.s -2 IL_0076: stfld ""int Script.<<Initialize>>d__0.<>1__state"" IL_007b: ldarg.0 IL_007c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> Script.<<Initialize>>d__0.<>t__builder"" IL_0081: ldloc.2 IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0087: leave.s IL_009d } IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Script.<<Initialize>>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> Script.<<Initialize>>d__0.<>t__builder"" IL_0097: ldloc.1 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_009d: ret }", realIL: true); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InScriptMethod() { var sourceLib = @" public class Color { public int F(int a) { return 1; } } "; var lib = CreateCompilation(sourceLib); string sourceScript = @" Color Color; void Goo() { dynamic x = Color.F((dynamic)1); } "; var script = CreateCompilationWithMscorlib45( new[] { Parse(sourceScript, options: TestOptions.Script) }, new[] { new CSharpCompilationReference(lib), SystemCoreRef, CSharpRef }, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(script).VerifyIL("Goo", @" { // Code size 99 (0x63) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0005: brtrue.s IL_0041 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""Script"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0037: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0046: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Target"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0050: ldarg.0 IL_0051: ldfld ""Color Script.Color"" IL_0056: ldc.i4.1 IL_0057: box ""int"" IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0061: pop IL_0062: ret } ", realIL: true); } [Fact] public void InvokeMember_UseCompileTimeType() { string source = @" class C { static char? nChar = null; static char Char = '\0'; static C c = new C(); static object obj = null; static dynamic d = new C(); static void M() { d.f(nChar); d.f(Char); d.f(c); d.f(obj); d.f(d); d.f(null); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 591 (0x24f) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.1 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, char?> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0054: ldsfld ""dynamic C.d"" IL_0059: ldsfld ""char? C.nChar"" IL_005e: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, char?>.Invoke(System.Runtime.CompilerServices.CallSite, object, char?)"" IL_0063: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_0068: brtrue.s IL_00a8 IL_006a: ldc.i4 0x100 IL_006f: ldstr ""f"" IL_0074: ldnull IL_0075: ldtoken ""C"" IL_007a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007f: ldc.i4.2 IL_0080: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0085: dup IL_0086: ldc.i4.0 IL_0087: ldc.i4.0 IL_0088: ldnull IL_0089: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008e: stelem.ref IL_008f: dup IL_0090: ldc.i4.1 IL_0091: ldc.i4.1 IL_0092: ldnull IL_0093: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0098: stelem.ref IL_0099: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00a8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00ad: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, char> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>>.Target"" IL_00b2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00b7: ldsfld ""dynamic C.d"" IL_00bc: ldsfld ""char C.Char"" IL_00c1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, char>.Invoke(System.Runtime.CompilerServices.CallSite, object, char)"" IL_00c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_00cb: brtrue.s IL_010b IL_00cd: ldc.i4 0x100 IL_00d2: ldstr ""f"" IL_00d7: ldnull IL_00d8: ldtoken ""C"" IL_00dd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00e2: ldc.i4.2 IL_00e3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e8: dup IL_00e9: ldc.i4.0 IL_00ea: ldc.i4.0 IL_00eb: ldnull IL_00ec: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f1: stelem.ref IL_00f2: dup IL_00f3: ldc.i4.1 IL_00f4: ldc.i4.1 IL_00f5: ldnull IL_00f6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00fb: stelem.ref IL_00fc: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0101: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0106: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_010b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_0110: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_0115: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_011a: ldsfld ""dynamic C.d"" IL_011f: ldsfld ""C C.c"" IL_0124: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object, C)"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_012e: brtrue.s IL_016e IL_0130: ldc.i4 0x100 IL_0135: ldstr ""f"" IL_013a: ldnull IL_013b: ldtoken ""C"" IL_0140: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0145: ldc.i4.2 IL_0146: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_014b: dup IL_014c: ldc.i4.0 IL_014d: ldc.i4.0 IL_014e: ldnull IL_014f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0154: stelem.ref IL_0155: dup IL_0156: ldc.i4.1 IL_0157: ldc.i4.1 IL_0158: ldnull IL_0159: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_015e: stelem.ref IL_015f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0164: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0169: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_016e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_0173: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0178: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_017d: ldsfld ""dynamic C.d"" IL_0182: ldsfld ""object C.obj"" IL_0187: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_018c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_0191: brtrue.s IL_01d1 IL_0193: ldc.i4 0x100 IL_0198: ldstr ""f"" IL_019d: ldnull IL_019e: ldtoken ""C"" IL_01a3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01a8: ldc.i4.2 IL_01a9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ae: dup IL_01af: ldc.i4.0 IL_01b0: ldc.i4.0 IL_01b1: ldnull IL_01b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01b7: stelem.ref IL_01b8: dup IL_01b9: ldc.i4.1 IL_01ba: ldc.i4.0 IL_01bb: ldnull IL_01bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c1: stelem.ref IL_01c2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c7: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01cc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01d6: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01e0: ldsfld ""dynamic C.d"" IL_01e5: ldsfld ""dynamic C.d"" IL_01ea: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01ef: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_01f4: brtrue.s IL_0234 IL_01f6: ldc.i4 0x100 IL_01fb: ldstr ""f"" IL_0200: ldnull IL_0201: ldtoken ""C"" IL_0206: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_020b: ldc.i4.2 IL_020c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0211: dup IL_0212: ldc.i4.0 IL_0213: ldc.i4.0 IL_0214: ldnull IL_0215: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_021a: stelem.ref IL_021b: dup IL_021c: ldc.i4.1 IL_021d: ldc.i4.2 IL_021e: ldnull IL_021f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0224: stelem.ref IL_0225: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_022a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_022f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0234: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0239: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_023e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0243: ldsfld ""dynamic C.d"" IL_0248: ldnull IL_0249: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_024e: ret } "); } [Fact] public void InvokeMember_UseCompileTimeType_ConvertedReceiver() { string source = @" class C { void M(object o) { (o as dynamic).f(); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 81 (0x51) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.1 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_0040: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_004a: ldarg.1 IL_004b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0050: ret } "); } [Fact] public void InvokeMember_Dynamic_Generic() { string source = @" public class C { public dynamic M(dynamic d) { return d.m<C, int>(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 119 (0x77) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0060 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldc.i4.2 IL_000e: newarr ""System.Type"" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: stelem.ref IL_0020: dup IL_0021: ldc.i4.1 IL_0022: ldtoken ""int"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: stelem.ref IL_002d: ldtoken ""C"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: ldc.i4.2 IL_0038: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003d: dup IL_003e: ldc.i4.0 IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0046: stelem.ref IL_0047: dup IL_0048: ldc.i4.1 IL_0049: ldc.i4.0 IL_004a: ldnull IL_004b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0050: stelem.ref IL_0051: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0056: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0065: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_006f: ldarg.1 IL_0070: ldarg.1 IL_0071: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0076: ret } "); } [Fact] public void InvokeMember_Static_Generic() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c.F<int, dynamic>(null, this, d); } public int F<T1, T2>(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 141 (0x8d) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0074 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldc.i4.2 IL_000e: newarr ""System.Type"" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldtoken ""int"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: stelem.ref IL_0020: dup IL_0021: ldc.i4.1 IL_0022: ldtoken ""object"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: stelem.ref IL_002d: ldtoken ""C"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: ldc.i4.4 IL_0038: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003d: dup IL_003e: ldc.i4.0 IL_003f: ldc.i4.1 IL_0040: ldnull IL_0041: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0046: stelem.ref IL_0047: dup IL_0048: ldc.i4.1 IL_0049: ldc.i4.2 IL_004a: ldnull IL_004b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0050: stelem.ref IL_0051: dup IL_0052: ldc.i4.2 IL_0053: ldc.i4.1 IL_0054: ldnull IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: dup IL_005c: ldc.i4.3 IL_005d: ldc.i4.0 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0079: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0083: ldarg.1 IL_0084: ldnull IL_0085: ldarg.0 IL_0086: ldarg.2 IL_0087: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_008c: ret } "); } [Fact] public void InvokeMember_Dynamic_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d, int a) { return d.m(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 123 (0x7b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0061 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.4 IL_002b: ldstr ""goo"" IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.5 IL_0039: ldstr ""bar"" IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.7 IL_0047: ldstr ""baz"" IL_004c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0051: stelem.ref IL_0052: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0057: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0061: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0066: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Target"" IL_006b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0070: ldarg.1 IL_0071: ldarg.1 IL_0072: ldarg.2 IL_0073: ldc.i4.s 123 IL_0075: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_007a: ret } "); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void InvokeMember_NamedArguments_PartialMethods() { string source = @" partial class C { static partial void F(int i); } partial class C { static partial void F(int j) { System.Console.WriteLine(j); } public static void Main() { dynamic d = 2; F(i: d); } } "; CompileAndVerifyWithCSharp(source, expectedOutput: "2"); } [Fact] public void InvokeMember_ManyArgs_F14() { string source = @" public class C { public dynamic M14(dynamic d) { return d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); } }"; CompileAndVerifyIL(source, "C.M14", @" { // Code size 247 (0xf7) .maxstack 17 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00cd IL_000a: ldc.i4.0 IL_000b: ldstr ""m"" IL_0010: ldnull IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.s 15 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.3 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: dup IL_004b: ldc.i4.4 IL_004c: ldc.i4.3 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.5 IL_0056: ldc.i4.3 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.6 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.7 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.8 IL_0074: ldc.i4.3 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.s 9 IL_007f: ldc.i4.3 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.s 10 IL_008a: ldc.i4.3 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.s 11 IL_0095: ldc.i4.3 IL_0096: ldnull IL_0097: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009c: stelem.ref IL_009d: dup IL_009e: ldc.i4.s 12 IL_00a0: ldc.i4.3 IL_00a1: ldnull IL_00a2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a7: stelem.ref IL_00a8: dup IL_00a9: ldc.i4.s 13 IL_00ab: ldc.i4.3 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.s 14 IL_00b6: ldc.i4.3 IL_00b7: ldnull IL_00b8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bd: stelem.ref IL_00be: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00cd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Target"" IL_00d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00dc: ldarg.1 IL_00dd: ldc.i4.1 IL_00de: ldc.i4.2 IL_00df: ldc.i4.3 IL_00e0: ldc.i4.4 IL_00e1: ldc.i4.5 IL_00e2: ldc.i4.6 IL_00e3: ldc.i4.7 IL_00e4: ldc.i4.8 IL_00e5: ldc.i4.s 9 IL_00e7: ldc.i4.s 10 IL_00e9: ldc.i4.s 11 IL_00eb: ldc.i4.s 12 IL_00ed: ldc.i4.s 13 IL_00ef: ldc.i4.s 14 IL_00f1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00f6: ret }"); } [Fact] public void InvokeMember_ManyArgs_F15() { // TODO: verify metadata of the synthesized delegate // TODO: use VerifyRealIL to check that dynamic is erased string source = @" public class C { public dynamic M15(dynamic d) { return d.m(1, true, 1.0, 'c', ""s"", (byte)1, (sbyte)1, (uint)1, (long)1, (ulong)1, (float)1.0, (decimal)1, default(System.DateTime), d, d); } }"; CompileAndVerifyIL(source, "C.M15", @" { // Code size 284 (0x11c) .maxstack 18 .locals init (System.DateTime V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d8 IL_000a: ldc.i4.0 IL_000b: ldstr ""m"" IL_0010: ldnull IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.s 16 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.3 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: dup IL_004b: ldc.i4.4 IL_004c: ldc.i4.3 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.5 IL_0056: ldc.i4.3 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.6 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.7 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.8 IL_0074: ldc.i4.3 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.s 9 IL_007f: ldc.i4.3 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.s 10 IL_008a: ldc.i4.3 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.s 11 IL_0095: ldc.i4.3 IL_0096: ldnull IL_0097: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009c: stelem.ref IL_009d: dup IL_009e: ldc.i4.s 12 IL_00a0: ldc.i4.3 IL_00a1: ldnull IL_00a2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a7: stelem.ref IL_00a8: dup IL_00a9: ldc.i4.s 13 IL_00ab: ldc.i4.1 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.s 14 IL_00b6: ldc.i4.0 IL_00b7: ldnull IL_00b8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bd: stelem.ref IL_00be: dup IL_00bf: ldc.i4.s 15 IL_00c1: ldc.i4.0 IL_00c2: ldnull IL_00c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c8: stelem.ref IL_00c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00ce: call ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d3: stsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00d8: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00dd: ldfld ""<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>>.Target"" IL_00e2: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00e7: ldarg.1 IL_00e8: ldc.i4.1 IL_00e9: ldc.i4.1 IL_00ea: ldc.r8 1 IL_00f3: ldc.i4.s 99 IL_00f5: ldstr ""s"" IL_00fa: ldc.i4.1 IL_00fb: ldc.i4.1 IL_00fc: ldc.i4.1 IL_00fd: ldc.i4.1 IL_00fe: conv.i8 IL_00ff: ldc.i4.1 IL_0100: conv.i8 IL_0101: ldc.r4 1 IL_0106: ldsfld ""decimal decimal.One"" IL_010b: ldloca.s V_0 IL_010d: initobj ""System.DateTime"" IL_0113: ldloc.0 IL_0114: ldarg.1 IL_0115: ldarg.1 IL_0116: callvirt ""object <>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object)"" IL_011b: ret } " ); } [Fact] public void InvokeMember_ManyArgs_A14() { string source = @" public class C { public void M14(dynamic d) { d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); } }"; CompileAndVerifyIL(source, "C.M14", @" { // Code size 251 (0xfb) .maxstack 17 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d1 IL_000a: ldc.i4 0x100 IL_000f: ldstr ""m"" IL_0014: ldnull IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.s 15 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.4 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.5 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.6 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.7 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.8 IL_0078: ldc.i4.3 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: dup IL_0081: ldc.i4.s 9 IL_0083: ldc.i4.3 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.s 10 IL_008e: ldc.i4.3 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: dup IL_0097: ldc.i4.s 11 IL_0099: ldc.i4.3 IL_009a: ldnull IL_009b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a0: stelem.ref IL_00a1: dup IL_00a2: ldc.i4.s 12 IL_00a4: ldc.i4.3 IL_00a5: ldnull IL_00a6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ab: stelem.ref IL_00ac: dup IL_00ad: ldc.i4.s 13 IL_00af: ldc.i4.3 IL_00b0: ldnull IL_00b1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b6: stelem.ref IL_00b7: dup IL_00b8: ldc.i4.s 14 IL_00ba: ldc.i4.3 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c7: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00d6: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Target"" IL_00db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00e0: ldarg.1 IL_00e1: ldc.i4.1 IL_00e2: ldc.i4.2 IL_00e3: ldc.i4.3 IL_00e4: ldc.i4.4 IL_00e5: ldc.i4.5 IL_00e6: ldc.i4.6 IL_00e7: ldc.i4.7 IL_00e8: ldc.i4.8 IL_00e9: ldc.i4.s 9 IL_00eb: ldc.i4.s 10 IL_00ed: ldc.i4.s 11 IL_00ef: ldc.i4.s 12 IL_00f1: ldc.i4.s 13 IL_00f3: ldc.i4.s 14 IL_00f5: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00fa: ret } "); } [Fact] public void InvokeMember_ManyArgs_A15() { string source = @" public class C { public void M15(dynamic d) { d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); } }"; CompileAndVerifyIL(source, "C.M15", @" { // Code size 264 (0x108) .maxstack 18 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00dc IL_000a: ldc.i4 0x100 IL_000f: ldstr ""m"" IL_0014: ldnull IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.s 16 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.4 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.5 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.6 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.7 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.8 IL_0078: ldc.i4.3 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: dup IL_0081: ldc.i4.s 9 IL_0083: ldc.i4.3 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.s 10 IL_008e: ldc.i4.3 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: dup IL_0097: ldc.i4.s 11 IL_0099: ldc.i4.3 IL_009a: ldnull IL_009b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a0: stelem.ref IL_00a1: dup IL_00a2: ldc.i4.s 12 IL_00a4: ldc.i4.3 IL_00a5: ldnull IL_00a6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ab: stelem.ref IL_00ac: dup IL_00ad: ldc.i4.s 13 IL_00af: ldc.i4.3 IL_00b0: ldnull IL_00b1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b6: stelem.ref IL_00b7: dup IL_00b8: ldc.i4.s 14 IL_00ba: ldc.i4.3 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: dup IL_00c3: ldc.i4.s 15 IL_00c5: ldc.i4.3 IL_00c6: ldnull IL_00c7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cc: stelem.ref IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00e1: ldfld ""<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int> System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00eb: ldarg.1 IL_00ec: ldc.i4.1 IL_00ed: ldc.i4.2 IL_00ee: ldc.i4.3 IL_00ef: ldc.i4.4 IL_00f0: ldc.i4.5 IL_00f1: ldc.i4.6 IL_00f2: ldc.i4.7 IL_00f3: ldc.i4.8 IL_00f4: ldc.i4.s 9 IL_00f6: ldc.i4.s 10 IL_00f8: ldc.i4.s 11 IL_00fa: ldc.i4.s 12 IL_00fc: ldc.i4.s 13 IL_00fe: ldc.i4.s 14 IL_0100: ldc.i4.s 15 IL_0102: callvirt ""void <>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_0107: ret } "); } [Fact] public void InvokeMember_ByRefArgs() { string source = @" public class C { public dynamic M(dynamic d) { return d.m(ref d, out d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_004d IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.3 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.s 9 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: dup IL_0034: ldc.i4.2 IL_0035: ldc.i4.s 17 IL_0037: ldnull IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0043: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0048: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_0052: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_0057: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_005c: ldarg.1 IL_005d: ldarga.s V_1 IL_005f: ldarga.s V_1 IL_0061: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref object)"" IL_0066: ret } "); } [Fact] public void InvokeMember_ByRefArgs_Runtime() { string source = @" public class C { public static dynamic d = new C(); public static void Main() { d.m(ref d, out d); } public void m(ref object a, out object b) { b = null; } } "; CompileAndVerifyWithCSharp(source, expectedOutput: ""); } /// <summary> /// By-ref dynamic argument doesn't make the call dynamic. /// </summary> [Fact] public void InvokeMember_ByRefDynamic() { string source = @" public class C { static dynamic d = true; public static void f(ref dynamic d) { } public static void M() { f(ref d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldsflda ""dynamic C.d"" IL_0005: call ""void C.f(ref dynamic)"" IL_000a: ret } "); } /// <summary> /// ref/out can be omitted at call-site. /// </summary> [Fact] public void InvokeMember_CallSiteRefOutOmitted() { string source = @" public class C { dynamic d = true; public void f(ref int a, out int b, ref dynamic c, out object d) { b = 1; d = null; } public void M() { object lo = null; dynamic ld; f(d, d, ref lo, out ld); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 141 (0x8d) .maxstack 9 .locals init (object V_0, //lo object V_1) //ld IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0007: brtrue.s IL_0067 IL_0009: ldc.i4 0x102 IL_000e: ldstr ""f"" IL_0013: ldnull IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.5 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: dup IL_0039: ldc.i4.2 IL_003a: ldc.i4.0 IL_003b: ldnull IL_003c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldc.i4.s 9 IL_0046: ldnull IL_0047: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004c: stelem.ref IL_004d: dup IL_004e: ldc.i4.4 IL_004f: ldc.i4.s 17 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_005d: call ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0062: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0067: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_006c: ldfld ""<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>>.Target"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0076: ldarg.0 IL_0077: ldarg.0 IL_0078: ldfld ""dynamic C.d"" IL_007d: ldarg.0 IL_007e: ldfld ""dynamic C.d"" IL_0083: ldloca.s V_0 IL_0085: ldloca.s V_1 IL_0087: callvirt ""void <>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, object, ref object, ref object)"" IL_008c: ret } "); } [Fact] public void InvokeStaticMember1() { string source = @" public class C { public void M(dynamic d) { D.F(d); } } public class D { public static void F(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""F"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0055: ldtoken ""D"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.1 IL_0060: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0065: ret }"); } [Fact] public void InvokeStaticMember2() { string source = @" public class C { static dynamic d = true; public static void f(dynamic d) { } public static void M() { f(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0055: ldtoken ""C"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.d"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0069: ret } "); } [Fact] [WorkItem(627091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627091")] public void InvokeStaticMember_InLambda() { string source = @" class C { static void Goo(dynamic x) { System.Action a = () => Goo(x); } } "; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0.<Goo>b__0", @" { // Code size 107 (0x6b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0055: ldtoken ""C"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0065: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_006a: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Local() { string source = @" public class C { public void M(dynamic d) { S s = new S(); s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 9 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_000d: brtrue.s IL_004e IL_000f: ldc.i4 0x100 IL_0014: ldstr ""goo"" IL_0019: ldnull IL_001a: ldtoken ""C"" IL_001f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0024: ldc.i4.2 IL_0025: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldc.i4.s 9 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: dup IL_0036: ldc.i4.1 IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003e: stelem.ref IL_003f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0044: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0049: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0053: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0058: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_005d: ldloca.s V_0 IL_005f: ldarg.1 IL_0060: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0065: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Parameter() { string source = @" public class C { public void M(S s, dynamic d) { s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 94 (0x5e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0055: ldarga.s V_1 IL_0057: ldarg.2 IL_0058: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_005d: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_This() { string source = @" public struct S { int a; public void M(dynamic d) { this.Equals(d); } } "; CompileAndVerifyIL(source, "S.M", @" { // Code size 93 (0x5d) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Equals"" IL_0011: ldnull IL_0012: ldtoken ""S"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0055: ldarg.0 IL_0056: ldarg.1 IL_0057: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_005c: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_FieldAccess() { string source = @" public class C { private S s; public void M(dynamic d) { s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0054: ldarg.0 IL_0055: ldfld ""S C.s"" IL_005a: ldarg.1 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_ArrayAccess() { string source = @" public class C { private S[] s; public void M(dynamic d) { s[0].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0055: ldarg.0 IL_0056: ldfld ""S[] C.s"" IL_005b: ldc.i4.0 IL_005c: ldelema ""S"" IL_0061: ldarg.1 IL_0062: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0067: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerIndirectionOperator1() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S s = new S(); S* ptr = &s; (*ptr).goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 105 (0x69) .maxstack 9 .locals init (S V_0, //s S* V_1) //ptr IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: stloc.1 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.1 IL_0062: ldarg.1 IL_0063: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0068: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerIndirectionOperator2() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S s = new S(); S* ptr = &s; ptr->goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 105 (0x69) .maxstack 9 .locals init (S V_0, //s S* V_1) //ptr IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: stloc.1 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.1 IL_0062: ldarg.1 IL_0063: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0068: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerElementAccess() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S* ptr = stackalloc S[2]; ptr[1].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 112 (0x70) .maxstack 9 .locals init (S* V_0) //ptr IL_0000: ldc.i4.2 IL_0001: conv.u IL_0002: sizeof ""S"" IL_0008: mul.ovf.un IL_0009: localloc IL_000b: stloc.0 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.0 IL_0062: sizeof ""S"" IL_0068: add IL_0069: ldarg.1 IL_006a: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_006f: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_TypeReference() { string source = @" using System; public class C { public void M(dynamic d) { int a = 1; TypedReference tr = __makeref(a); __refvalue(tr, int).Equals(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 108 (0x6c) .maxstack 9 .locals init (int V_0, //a System.TypedReference V_1) //tr IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: stloc.1 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_000f: brtrue.s IL_0050 IL_0011: ldc.i4 0x100 IL_0016: ldstr ""Equals"" IL_001b: ldnull IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.2 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.s 9 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.1 IL_0039: ldc.i4.0 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0046: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004b: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_0055: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>>.Target"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_005f: ldloc.1 IL_0060: refanyval ""int"" IL_0065: ldarg.1 IL_0066: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref int, object)"" IL_006b: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_Literal() { string source = @" public class C { public void M(dynamic d) { ""a"".Equals(d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 96 (0x60) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Equals"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, string, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0054: ldstr ""a"" IL_0059: ldarg.1 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, string, object>.Invoke(System.Runtime.CompilerServices.CallSite, string, object)"" IL_005f: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_Assignment() { string source = @" public class C { public void M(dynamic d, S s, S t) { (s = t).goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 95 (0x5f) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.3 IL_0055: dup IL_0056: starg.s V_2 IL_0058: ldarg.1 IL_0059: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_005e: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_PropertyAccess() { string source = @" public class C { private S P { get; set; } public void M(C c, dynamic d) { c.P.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0054: ldarg.1 IL_0055: callvirt ""S C.P.get"" IL_005a: ldarg.2 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_IndexerAccess() { string source = @" public class C { private S this[int index] { get { return new S(); } set { } } public void M(C c, dynamic d) { c[0].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 98 (0x62) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0054: ldarg.1 IL_0055: ldc.i4.0 IL_0056: callvirt ""S C.this[int].get"" IL_005b: ldarg.2 IL_005c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0061: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Invocation() { string source = @" public class C { public void M(System.Func<S> f, dynamic d) { f().goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.1 IL_0055: callvirt ""S System.Func<S>.Invoke()"" IL_005a: ldarg.2 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret }"); } [Fact] public void InvokeMember_InvokeMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.f().g(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 152 (0x98) .maxstack 11 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""g"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004b: brtrue.s IL_007d IL_004d: ldc.i4.0 IL_004e: ldstr ""f"" IL_0053: ldnull IL_0054: ldtoken ""C"" IL_0059: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005e: ldc.i4.1 IL_005f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0064: dup IL_0065: ldc.i4.0 IL_0066: ldc.i4.0 IL_0067: ldnull IL_0068: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006d: stelem.ref IL_006e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0073: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0078: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0082: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0087: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008c: ldarg.1 IL_008d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0092: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0097: ret }"); } [Fact] public void InvokeConstructor() { string source = @" public class C { public D M(dynamic d) { return new D(d); } } public class D { public D(int x) {} public D(string x) {} public D(string x, string y) {} }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 33 IL_001c: ldnull IL_001d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0022: stelem.ref IL_0023: dup IL_0024: ldc.i4.1 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_0041: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_004b: ldtoken ""D"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: ldarg.1 IL_0056: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_005b: ret } "); } [Fact] public void Invoke_Dynamic() { string source = @" public class C { public dynamic M(dynamic d, int a) { return d(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 117 (0x75) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_005b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.4 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.4 IL_0025: ldstr ""goo"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.5 IL_0033: ldstr ""bar"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.7 IL_0041: ldstr ""baz"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0051: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0056: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0060: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Target"" IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_006a: ldarg.1 IL_006b: ldarg.1 IL_006c: ldarg.2 IL_006d: ldc.i4.s 123 IL_006f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_0074: ret } "); } [Fact] public void Invoke_Dynamic_DiscardResult() { string source = @" public class C { public void M(dynamic d, int a) { d(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 121 (0x79) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_005f IL_0007: ldc.i4 0x100 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.4 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.4 IL_0029: ldstr ""goo"" IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: dup IL_0035: ldc.i4.2 IL_0036: ldc.i4.5 IL_0037: ldstr ""bar"" IL_003c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldc.i4.7 IL_0045: ldstr ""baz"" IL_004a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004f: stelem.ref IL_0050: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0055: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_0064: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>>.Target"" IL_0069: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_006e: ldarg.1 IL_006f: ldarg.1 IL_0070: ldarg.2 IL_0071: ldc.i4.s 123 IL_0073: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_0078: ret } "); } [Fact] public void Invoke_DynamicMember() { const string source = @" class C { dynamic d = null; void M(C c) { c.d(1); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 91 (0x5b) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_003f IL_0007: ldc.i4 0x100 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.2 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0035: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0044: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_004e: ldarg.1 IL_004f: ldfld ""dynamic C.d"" IL_0054: ldc.i4.1 IL_0055: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_005a: ret }"); } [Fact] public void Invoke_Static() { string source = @" public delegate int F(int a, bool b, C c); public class C { public dynamic M(F f, dynamic d) { return f(d, d, d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_004f IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.4 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0045: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_0054: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>>.Target"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_005e: ldarg.1 IL_005f: ldarg.2 IL_0060: ldarg.2 IL_0061: ldarg.2 IL_0062: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, F, object, object, object)"" IL_0067: ret } "); } [Fact] public void Invoke_Invoke() { string source = @" public class C { public dynamic M(dynamic d) { return d()(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 140 (0x8c) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0031 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.1 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0045: brtrue.s IL_0071 IL_0047: ldc.i4.0 IL_0048: ldtoken ""C"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.1 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.0 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0080: ldarg.1 IL_0081: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0086: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008b: ret }"); } [Fact] public void TypeInferenceGenericParameterTainting() { string source = @" using System.Collections.Generic; class C { public void F<T>(Dictionary<T, dynamic> d) { } static void M(C c, Dictionary<dynamic, dynamic> d) { c.F(d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""void C.F<object>(System.Collections.Generic.Dictionary<object, dynamic>)"" IL_0007: ret } "); } [Fact] public void InvokeMember_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static object Goo(object x) { return x; } }"; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 168 (0xa8) .maxstack 12 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_007e IL_0043: ldc.i4.0 IL_0044: ldstr ""Goo"" IL_0049: ldnull IL_004a: ldtoken ""C"" IL_004f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0054: ldc.i4.2 IL_0055: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005a: dup IL_005b: ldc.i4.0 IL_005c: ldc.i4.s 33 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: dup IL_0066: ldc.i4.1 IL_0067: ldc.i4.0 IL_0068: ldnull IL_0069: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006e: stelem.ref IL_006f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0074: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0079: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_0083: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Target"" IL_0088: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_008d: ldtoken ""C"" IL_0092: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0097: ldarg.1 IL_0098: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_009d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a2: call ""B..ctor(int)"" IL_00a7: ret } "); } [Fact] public void Invoke_Field_InConstructorInitializer() { string source = @" using System; class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static Action<object> Goo; } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 156 (0x9c) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_0077 IL_0043: ldc.i4.0 IL_0044: ldtoken ""C"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: ldc.i4.2 IL_004f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0054: dup IL_0055: ldc.i4.0 IL_0056: ldc.i4.1 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0072: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0077: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_007c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Target"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0086: ldsfld ""System.Action<object> C.Goo"" IL_008b: ldarg.1 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Action<object>, object)"" IL_0091: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: call ""B..ctor(int)"" IL_009b: ret } "); } [Fact] public void Invoke_Property_InConstructorInitializer() { string source = @" using System; class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static Action<object> Goo { get; set; } } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 156 (0x9c) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_0077 IL_0043: ldc.i4.0 IL_0044: ldtoken ""C"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: ldc.i4.2 IL_004f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0054: dup IL_0055: ldc.i4.0 IL_0056: ldc.i4.1 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0072: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0077: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_007c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Target"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0086: call ""System.Action<object> C.Goo.get"" IL_008b: ldarg.1 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Action<object>, object)"" IL_0091: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: call ""B..ctor(int)"" IL_009b: ret } "); } #endregion #region GetMember, GetIndex, SetMember, SetIndex [Fact] public void GetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0045: ldarg.1 IL_0046: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004b: ret } "); } [Fact] public void GetMember_GetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m.n; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 150 (0x96) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""n"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004a: brtrue.s IL_007b IL_004c: ldc.i4.0 IL_004d: ldstr ""m"" IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.1 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0071: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0076: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0080: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008a: ldarg.1 IL_008b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0090: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0095: ret } "); } [Fact] public void GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d[1]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 82 (0x52) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004a: ldarg.1 IL_004b: ldc.i4.1 IL_004c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0051: ret } "); } [Fact] public void GetMember_GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d.m[1]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 157 (0x9d) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_0081 IL_0051: ldc.i4.s 64 IL_0053: ldstr ""m"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.1 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0090: ldarg.1 IL_0091: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: ldc.i4.1 IL_0097: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_009c: ret } "); } [Fact] public void GetIndex_GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d[1][2]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 162 (0xa2) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_0085 IL_0051: ldc.i4.0 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.2 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0080: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_008a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0094: ldarg.1 IL_0095: ldc.i4.1 IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_009b: ldc.i4.2 IL_009c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00a1: ret } "); } [Fact] public void GetIndex_ManyArgs_F15() { string source = @" public class C { public dynamic M(dynamic d) { return d[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 254 (0xfe) .maxstack 18 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d2 IL_000a: ldc.i4.0 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldc.i4.s 16 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.3 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.4 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.5 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.6 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.7 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.8 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.s 9 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.s 10 IL_0084: ldc.i4.3 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.s 11 IL_008f: ldc.i4.3 IL_0090: ldnull IL_0091: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0096: stelem.ref IL_0097: dup IL_0098: ldc.i4.s 12 IL_009a: ldc.i4.3 IL_009b: ldnull IL_009c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a1: stelem.ref IL_00a2: dup IL_00a3: ldc.i4.s 13 IL_00a5: ldc.i4.3 IL_00a6: ldnull IL_00a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ac: stelem.ref IL_00ad: dup IL_00ae: ldc.i4.s 14 IL_00b0: ldc.i4.3 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: dup IL_00b9: ldc.i4.s 15 IL_00bb: ldc.i4.3 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cd: stsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d7: ldfld ""<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Target"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00e1: ldarg.1 IL_00e2: ldc.i4.1 IL_00e3: ldc.i4.2 IL_00e4: ldc.i4.3 IL_00e5: ldc.i4.4 IL_00e6: ldc.i4.5 IL_00e7: ldc.i4.6 IL_00e8: ldc.i4.7 IL_00e9: ldc.i4.8 IL_00ea: ldc.i4.s 9 IL_00ec: ldc.i4.s 10 IL_00ee: ldc.i4.s 11 IL_00f0: ldc.i4.s 12 IL_00f2: ldc.i4.s 13 IL_00f4: ldc.i4.s 14 IL_00f6: ldc.i4.s 15 IL_00f8: callvirt ""object <>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00fd: ret } "); } [Fact] public void GetIndex_ByRef() { string source = @" public class C { public dynamic M(dynamic d) { return d[ref d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0041: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004b: ldarg.1 IL_004c: ldarga.s V_1 IL_004e: callvirt ""object <>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object)"" IL_0053: ret } "); } [Fact] public void GetIndex_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d) { return d[a: 1, b: d, c: null, d: ref d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 133 (0x85) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_006a IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.5 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.7 IL_0025: ldstr ""a"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.4 IL_0033: ldstr ""b"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.6 IL_0041: ldstr ""c"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: dup IL_004d: ldc.i4.4 IL_004e: ldc.i4.s 13 IL_0050: ldstr ""d"" IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0060: call ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0065: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_006f: ldfld ""<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>>.Target"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0079: ldarg.1 IL_007a: ldc.i4.1 IL_007b: ldarg.1 IL_007c: ldnull IL_007d: ldarga.s V_1 IL_007f: callvirt ""object <>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object, object, ref object)"" IL_0084: ret } "); } [Fact] public void GetIndex_StaticReceiver() { string source = @" public class C { C a, b; int this[int i] { get { return 0; } set { } } public dynamic M(dynamic d) { return a.b[d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_004a: ldarg.0 IL_004b: ldfld ""C C.a"" IL_0050: ldfld ""C C.b"" IL_0055: ldarg.1 IL_0056: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_005b: ret } "); } [Fact] public void GetIndex_IndexedProperty() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public ReadOnly Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d]; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 167 (0xa7) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_004f: brtrue.s IL_0081 IL_0051: ldc.i4.s 64 IL_0053: ldstr ""IndexedProperty"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.1 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.1 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0090: ldarg.0 IL_0091: ldfld ""B C.b"" IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_009b: ldarg.0 IL_009c: ldfld ""dynamic C.d"" IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00a6: ret }"); } [Fact] public void SetIndex_IndexedProperty() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get Set End Set End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d] = 42; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 179 (0xb3) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.3 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0059: brtrue.s IL_008b IL_005b: ldc.i4.s 64 IL_005d: ldstr ""IndexedProperty"" IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.1 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_009a: ldarg.0 IL_009b: ldfld ""B C.b"" IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_00a5: ldarg.0 IL_00a6: ldfld ""dynamic C.d"" IL_00ab: ldc.i4.s 42 IL_00ad: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_00b2: ret }"); } [Fact] public void SetIndex_IndexedProperty_CompoundAssignment() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get Set End Set End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d] += 42; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 424 (0x1a8) .maxstack 16 .locals init (B V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""dynamic C.d"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0013: brtrue.s IL_0057 IL_0015: ldc.i4 0x80 IL_001a: ldtoken ""C"" IL_001f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0024: ldc.i4.3 IL_0025: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: dup IL_0035: ldc.i4.1 IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.2 IL_0040: ldc.i4.0 IL_0041: ldnull IL_0042: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0047: stelem.ref IL_0048: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0052: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0057: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_005c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_0061: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0066: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_006b: brtrue.s IL_009d IL_006d: ldc.i4.s 64 IL_006f: ldstr ""IndexedProperty"" IL_0074: ldtoken ""C"" IL_0079: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007e: ldc.i4.1 IL_007f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0084: dup IL_0085: ldc.i4.0 IL_0086: ldc.i4.1 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_00a2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_00ac: ldloc.0 IL_00ad: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_00b2: ldloc.1 IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00b8: brtrue.s IL_00f0 IL_00ba: ldc.i4.0 IL_00bb: ldc.i4.s 63 IL_00bd: ldtoken ""C"" IL_00c2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c7: ldc.i4.2 IL_00c8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00cd: dup IL_00ce: ldc.i4.0 IL_00cf: ldc.i4.0 IL_00d0: ldnull IL_00d1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d6: stelem.ref IL_00d7: dup IL_00d8: ldc.i4.1 IL_00d9: ldc.i4.3 IL_00da: ldnull IL_00db: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e0: stelem.ref IL_00e1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00e6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00eb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00f0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00f5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00fa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00ff: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0104: brtrue.s IL_013a IL_0106: ldc.i4.0 IL_0107: ldtoken ""C"" IL_010c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0111: ldc.i4.2 IL_0112: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0117: dup IL_0118: ldc.i4.0 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: dup IL_0122: ldc.i4.1 IL_0123: ldc.i4.0 IL_0124: ldnull IL_0125: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012a: stelem.ref IL_012b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0130: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0135: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_013f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0144: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_014e: brtrue.s IL_0180 IL_0150: ldc.i4.s 64 IL_0152: ldstr ""IndexedProperty"" IL_0157: ldtoken ""C"" IL_015c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0161: ldc.i4.1 IL_0162: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0167: dup IL_0168: ldc.i4.0 IL_0169: ldc.i4.1 IL_016a: ldnull IL_016b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0170: stelem.ref IL_0171: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0176: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_017b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0180: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0185: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_018a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_018f: ldloc.0 IL_0190: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_0195: ldloc.1 IL_0196: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_019b: ldc.i4.s 42 IL_019d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_01a7: ret } "); } [Fact] public void GetIndex_IndexerWithByRefParam() { var ilRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Interop.IndexerWithByRefParam.AsImmutableOrNull()); string source = @" class C { B b; dynamic d; object M() { return b[d]; } } "; CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, ilRef }, expectedOptimizedIL: @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_004a: ldarg.0 IL_004b: ldfld ""B C.b"" IL_0050: ldarg.0 IL_0051: ldfld ""dynamic C.d"" IL_0056: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_005b: ret } "); } [Fact] public void SetIndex_SetIndex_Receiver() { string source = @" public class C { public dynamic M(dynamic d) { return (d[1] = d)[2]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 173 (0xad) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_008f IL_0051: ldc.i4.0 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.3 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.2 IL_0078: ldc.i4.0 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0085: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_0094: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_0099: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_009e: ldarg.1 IL_009f: ldc.i4.1 IL_00a0: ldarg.1 IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_00a6: ldc.i4.2 IL_00a7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00ac: ret } "); } [Fact] public void SetIndex_SetIndex_Argument() { string source = @" public class C { public dynamic M(dynamic d) { return d[d[d] = d] = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 184 (0xb8) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.3 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0054: ldarg.1 IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_005a: brtrue.s IL_009a IL_005c: ldc.i4.0 IL_005d: ldtoken ""C"" IL_0062: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0067: ldc.i4.3 IL_0068: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006d: dup IL_006e: ldc.i4.0 IL_006f: ldc.i4.0 IL_0070: ldnull IL_0071: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0076: stelem.ref IL_0077: dup IL_0078: ldc.i4.1 IL_0079: ldc.i4.0 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.2 IL_0083: ldc.i4.0 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0090: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0095: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_009f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_00a9: ldarg.1 IL_00aa: ldarg.1 IL_00ab: ldarg.1 IL_00ac: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_00b1: ldarg.1 IL_00b2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_00b7: ret } "); } [Fact] public void SetIndex_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d) { return d[a: d, b: 0, c: null, d: out d] = null; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 144 (0x90) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0074 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.6 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.4 IL_0025: ldstr ""a"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.7 IL_0033: ldstr ""b"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.6 IL_0041: ldstr ""c"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: dup IL_004d: ldc.i4.4 IL_004e: ldc.i4.s 21 IL_0050: ldstr ""d"" IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: dup IL_005c: ldc.i4.5 IL_005d: ldc.i4.2 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0079: ldfld ""<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0083: ldarg.1 IL_0084: ldarg.1 IL_0085: ldc.i4.0 IL_0086: ldnull IL_0087: ldarga.s V_1 IL_0089: ldnull IL_008a: callvirt ""object <>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object, ref object, object)"" IL_008f: ret } "); } [Fact] public void SetIndex_ValueTypeReceiver_Local() { string source = @" public class C { public void M(dynamic d) { S s = new S(); s[d] = 1; } } public struct S { public int X; public int this[int index] { get { return index; } set { } } } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 7 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_000d: brtrue.s IL_004e IL_000f: ldc.i4.0 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.3 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.s 9 IL_0024: ldnull IL_0025: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002a: stelem.ref IL_002b: dup IL_002c: ldc.i4.1 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: dup IL_0036: ldc.i4.2 IL_0037: ldc.i4.3 IL_0038: ldnull IL_0039: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003e: stelem.ref IL_003f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0044: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0049: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_0053: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>>.Target"" IL_0058: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_005d: ldloca.s V_0 IL_005f: ldarg.1 IL_0060: ldc.i4.1 IL_0061: callvirt ""object <>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object, int)"" IL_0066: pop IL_0067: ret }"); } [Fact] public void SetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0040 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.2 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: dup IL_0028: ldc.i4.1 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0036: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0045: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004f: ldarg.1 IL_0050: ldarg.1 IL_0051: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0056: ret } "); } [Fact] public void SetMember_SetMember() { string source = @" public class C { public dynamic M(dynamic d) { return (d.a = d).b = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 172 (0xac) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0040 IL_0007: ldc.i4.0 IL_0008: ldstr ""b"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.2 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: dup IL_0028: ldc.i4.1 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0036: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0045: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0054: brtrue.s IL_008f IL_0056: ldc.i4.0 IL_0057: ldstr ""a"" IL_005c: ldtoken ""C"" IL_0061: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0066: ldc.i4.2 IL_0067: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006c: dup IL_006d: ldc.i4.0 IL_006e: ldc.i4.0 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.1 IL_0078: ldc.i4.0 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0085: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0094: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0099: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_009e: ldarg.1 IL_009f: ldarg.1 IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00a5: ldarg.1 IL_00a6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00ab: ret } "); } #endregion #region Assignment [Fact] public void AssignmentRhsConversion() { string source = @" public class C { public void M(dynamic p) { dynamic d = 1; p = 2; d.f = 1.0; p[2] = 'c'; } } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 205 (0xcd) .maxstack 8 .locals init (object V_0) //d IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldc.i4.2 IL_0008: box ""int"" IL_000d: starg.s V_1 IL_000f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_0014: brtrue.s IL_004f IL_0016: ldc.i4.0 IL_0017: ldstr ""f"" IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.2 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.1 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0045: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_0054: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, double, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>>.Target"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_005e: ldloc.0 IL_005f: ldc.r8 1 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, double)"" IL_006d: pop IL_006e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_0073: brtrue.s IL_00b3 IL_0075: ldc.i4.0 IL_0076: ldtoken ""C"" IL_007b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0080: ldc.i4.3 IL_0081: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0086: dup IL_0087: ldc.i4.0 IL_0088: ldc.i4.0 IL_0089: ldnull IL_008a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008f: stelem.ref IL_0090: dup IL_0091: ldc.i4.1 IL_0092: ldc.i4.3 IL_0093: ldnull IL_0094: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0099: stelem.ref IL_009a: dup IL_009b: ldc.i4.2 IL_009c: ldc.i4.3 IL_009d: ldnull IL_009e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a3: stelem.ref IL_00a4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00ae: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00b8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>>.Target"" IL_00bd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00c2: ldarg.1 IL_00c3: ldc.i4.2 IL_00c4: ldc.i4.s 99 IL_00c6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, char)"" IL_00cb: pop IL_00cc: ret } "); } [Fact] public void CompoundDynamicMemberAssignment() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 259 (0x103) .maxstack 13 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_000c: brtrue.s IL_004b IL_000e: ldc.i4 0x80 IL_0013: ldstr ""m"" IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_005a: ldloc.0 IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0060: brtrue.s IL_0098 IL_0062: ldc.i4.0 IL_0063: ldc.i4.s 69 IL_0065: ldtoken ""C"" IL_006a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006f: ldc.i4.2 IL_0070: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0075: dup IL_0076: ldc.i4.0 IL_0077: ldc.i4.0 IL_0078: ldnull IL_0079: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007e: stelem.ref IL_007f: dup IL_0080: ldc.i4.1 IL_0081: ldc.i4.0 IL_0082: ldnull IL_0083: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0088: stelem.ref IL_0089: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_008e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0093: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_009d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00a2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ac: brtrue.s IL_00dd IL_00ae: ldc.i4.0 IL_00af: ldstr ""m"" IL_00b4: ldtoken ""C"" IL_00b9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00be: ldc.i4.1 IL_00bf: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c4: dup IL_00c5: ldc.i4.0 IL_00c6: ldc.i4.0 IL_00c7: ldnull IL_00c8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cd: stelem.ref IL_00ce: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00e2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ec: ldloc.0 IL_00ed: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00f2: ldarg.0 IL_00f3: ldfld ""dynamic C.v"" IL_00f8: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00fd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0102: ret }"); } [Fact] public void CompoundDynamicMemberAssignment_PossibleAddHandler() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 424 (0x1a8) .maxstack 11 .locals init (object V_0, bool V_1, object V_2, object V_3) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldarg.0 IL_0093: ldfld ""dynamic C.v"" IL_0098: stloc.3 IL_0099: ldloc.1 IL_009a: brtrue IL_014c IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00a4: brtrue.s IL_00e3 IL_00a6: ldc.i4 0x80 IL_00ab: ldstr ""m"" IL_00b0: ldtoken ""C"" IL_00b5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ba: ldc.i4.2 IL_00bb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldc.i4.0 IL_00c3: ldnull IL_00c4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c9: stelem.ref IL_00ca: dup IL_00cb: ldc.i4.1 IL_00cc: ldc.i4.0 IL_00cd: ldnull IL_00ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d3: stelem.ref IL_00d4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00de: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00f2: ldloc.0 IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_00f8: brtrue.s IL_0130 IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.s 63 IL_00fd: ldtoken ""C"" IL_0102: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0107: ldc.i4.2 IL_0108: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_010d: dup IL_010e: ldc.i4.0 IL_010f: ldc.i4.0 IL_0110: ldnull IL_0111: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0116: stelem.ref IL_0117: dup IL_0118: ldc.i4.1 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0126: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0130: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0135: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_013f: ldloc.2 IL_0140: ldloc.3 IL_0141: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0146: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_014b: ret IL_014c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0151: brtrue.s IL_0191 IL_0153: ldc.i4 0x104 IL_0158: ldstr ""add_m"" IL_015d: ldnull IL_015e: ldtoken ""C"" IL_0163: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0168: ldc.i4.2 IL_0169: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_016e: dup IL_016f: ldc.i4.0 IL_0170: ldc.i4.0 IL_0171: ldnull IL_0172: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0177: stelem.ref IL_0178: dup IL_0179: ldc.i4.1 IL_017a: ldc.i4.0 IL_017b: ldnull IL_017c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0181: stelem.ref IL_0182: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0187: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_018c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0196: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_019b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_01a0: ldloc.0 IL_01a1: ldloc.3 IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a7: ret } "); } [Fact] public void CompoundDynamicMemberAssignment_PossibleRemoveHandlerNull() { string source = @" public class C { dynamic d; public void M() { d.m -= null; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 419 (0x1a3) .maxstack 11 .locals init (object V_0, bool V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldloc.1 IL_0093: brtrue IL_0146 IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_009d: brtrue.s IL_00dc IL_009f: ldc.i4 0x80 IL_00a4: ldstr ""m"" IL_00a9: ldtoken ""C"" IL_00ae: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b3: ldc.i4.2 IL_00b4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b9: dup IL_00ba: ldc.i4.0 IL_00bb: ldc.i4.0 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: dup IL_00c4: ldc.i4.1 IL_00c5: ldc.i4.0 IL_00c6: ldnull IL_00c7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cc: stelem.ref IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00eb: ldloc.0 IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_00f1: brtrue.s IL_0129 IL_00f3: ldc.i4.0 IL_00f4: ldc.i4.s 73 IL_00f6: ldtoken ""C"" IL_00fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0100: ldc.i4.2 IL_0101: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldc.i4.0 IL_0109: ldnull IL_010a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010f: stelem.ref IL_0110: dup IL_0111: ldc.i4.1 IL_0112: ldc.i4.2 IL_0113: ldnull IL_0114: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0119: stelem.ref IL_011a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_011f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0124: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_012e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0133: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_0138: ldloc.2 IL_0139: ldnull IL_013a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_013f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0144: pop IL_0145: ret IL_0146: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_014b: brtrue.s IL_018b IL_014d: ldc.i4 0x104 IL_0152: ldstr ""remove_m"" IL_0157: ldnull IL_0158: ldtoken ""C"" IL_015d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0162: ldc.i4.2 IL_0163: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0168: dup IL_0169: ldc.i4.0 IL_016a: ldc.i4.0 IL_016b: ldnull IL_016c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0171: stelem.ref IL_0172: dup IL_0173: ldc.i4.1 IL_0174: ldc.i4.2 IL_0175: ldnull IL_0176: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_017b: stelem.ref IL_017c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0181: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0186: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_018b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0190: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0195: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_019a: ldloc.0 IL_019b: ldnull IL_019c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a1: pop IL_01a2: ret } "); } [Fact] public void CompoundDynamicMemberAssignment_PossibleRemoveHandler() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m -= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 424 (0x1a8) .maxstack 11 .locals init (object V_0, bool V_1, object V_2, object V_3) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldarg.0 IL_0093: ldfld ""dynamic C.v"" IL_0098: stloc.3 IL_0099: ldloc.1 IL_009a: brtrue IL_014c IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00a4: brtrue.s IL_00e3 IL_00a6: ldc.i4 0x80 IL_00ab: ldstr ""m"" IL_00b0: ldtoken ""C"" IL_00b5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ba: ldc.i4.2 IL_00bb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldc.i4.0 IL_00c3: ldnull IL_00c4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c9: stelem.ref IL_00ca: dup IL_00cb: ldc.i4.1 IL_00cc: ldc.i4.0 IL_00cd: ldnull IL_00ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d3: stelem.ref IL_00d4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00de: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00f2: ldloc.0 IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_00f8: brtrue.s IL_0130 IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.s 73 IL_00fd: ldtoken ""C"" IL_0102: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0107: ldc.i4.2 IL_0108: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_010d: dup IL_010e: ldc.i4.0 IL_010f: ldc.i4.0 IL_0110: ldnull IL_0111: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0116: stelem.ref IL_0117: dup IL_0118: ldc.i4.1 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0126: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0130: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0135: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_013f: ldloc.2 IL_0140: ldloc.3 IL_0141: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0146: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_014b: ret IL_014c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0151: brtrue.s IL_0191 IL_0153: ldc.i4 0x104 IL_0158: ldstr ""remove_m"" IL_015d: ldnull IL_015e: ldtoken ""C"" IL_0163: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0168: ldc.i4.2 IL_0169: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_016e: dup IL_016f: ldc.i4.0 IL_0170: ldc.i4.0 IL_0171: ldnull IL_0172: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0177: stelem.ref IL_0178: dup IL_0179: ldc.i4.1 IL_017a: ldc.i4.0 IL_017b: ldnull IL_017c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0181: stelem.ref IL_0182: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0187: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_018c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0196: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_019b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_01a0: ldloc.0 IL_01a1: ldloc.3 IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a7: ret } "); } [Fact] public void CompoundStaticFieldAssignment() { string source = @" public class C { public dynamic Field; C c; dynamic v; public dynamic M() { return c.Field *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 .locals init (C V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.c"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 69 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_0054: ldloc.0 IL_0055: ldfld ""dynamic C.Field"" IL_005a: ldarg.0 IL_005b: ldfld ""dynamic C.v"" IL_0060: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0065: dup IL_0066: stloc.1 IL_0067: stfld ""dynamic C.Field"" IL_006c: ldloc.1 IL_006d: ret }"); } [Fact] public void CompoundStaticPropertyAssignment() { string source = @" public class C { public dynamic Property { get; set; } C c; dynamic v; public dynamic M() { return c.Property *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 .locals init (C V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.c"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 69 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_0054: ldloc.0 IL_0055: callvirt ""dynamic C.Property.get"" IL_005a: ldarg.0 IL_005b: ldfld ""dynamic C.v"" IL_0060: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0065: dup IL_0066: stloc.1 IL_0067: callvirt ""void C.Property.set"" IL_006c: ldloc.1 IL_006d: ret } "); } [Fact] public void CompoundDynamicIndexerAssignment() { string source = @" public class C { public int f() { return 1; } public dynamic M(dynamic d, dynamic i, dynamic v) { return d[i, f()] *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 292 (0x124) .maxstack 14 .locals init (object V_0, object V_1, int V_2) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldarg.2 IL_0003: stloc.1 IL_0004: ldarg.0 IL_0005: call ""int C.f()"" IL_000a: stloc.2 IL_000b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_0010: brtrue.s IL_005e IL_0012: ldc.i4 0x80 IL_0017: ldtoken ""C"" IL_001c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0021: ldc.i4.4 IL_0022: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0027: dup IL_0028: ldc.i4.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: dup IL_0032: ldc.i4.1 IL_0033: ldc.i4.0 IL_0034: ldnull IL_0035: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003a: stelem.ref IL_003b: dup IL_003c: ldc.i4.2 IL_003d: ldc.i4.1 IL_003e: ldnull IL_003f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0044: stelem.ref IL_0045: dup IL_0046: ldc.i4.3 IL_0047: ldc.i4.0 IL_0048: ldnull IL_0049: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004e: stelem.ref IL_004f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0054: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0059: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_005e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_0063: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Target"" IL_0068: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_006d: ldloc.0 IL_006e: ldloc.1 IL_006f: ldloc.2 IL_0070: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0075: brtrue.s IL_00ad IL_0077: ldc.i4.0 IL_0078: ldc.i4.s 69 IL_007a: ldtoken ""C"" IL_007f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0084: ldc.i4.2 IL_0085: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_008a: dup IL_008b: ldc.i4.0 IL_008c: ldc.i4.0 IL_008d: ldnull IL_008e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0093: stelem.ref IL_0094: dup IL_0095: ldc.i4.1 IL_0096: ldc.i4.0 IL_0097: ldnull IL_0098: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009d: stelem.ref IL_009e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00ad: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00b2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00b7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_00c1: brtrue.s IL_0101 IL_00c3: ldc.i4.0 IL_00c4: ldtoken ""C"" IL_00c9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ce: ldc.i4.3 IL_00cf: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d4: dup IL_00d5: ldc.i4.0 IL_00d6: ldc.i4.0 IL_00d7: ldnull IL_00d8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00dd: stelem.ref IL_00de: dup IL_00df: ldc.i4.1 IL_00e0: ldc.i4.0 IL_00e1: ldnull IL_00e2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e7: stelem.ref IL_00e8: dup IL_00e9: ldc.i4.2 IL_00ea: ldc.i4.1 IL_00eb: ldnull IL_00ec: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f1: stelem.ref IL_00f2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f7: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0101: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0106: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_010b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0110: ldloc.0 IL_0111: ldloc.1 IL_0112: ldloc.2 IL_0113: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_0118: ldarg.3 IL_0119: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_011e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object)"" IL_0123: ret } "); #if TODO // locals and parameters shouldn't be spilled @"{ // Code size 288 (0x120) .maxstack 14 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""int C.f()"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_000c: brtrue.s IL_005a IL_000e: ldc.i4 0x80 IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.4 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: dup IL_0042: ldc.i4.3 IL_0043: ldc.i4.0 IL_0044: ldnull IL_0045: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004a: stelem.ref IL_004b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0050: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0055: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_005f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Target"" IL_0064: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_0069: ldarg.1 IL_006a: ldarg.2 IL_006b: ldloc.0 IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0071: brtrue.s IL_00a9 IL_0073: ldc.i4.0 IL_0074: ldc.i4.s 69 IL_0076: ldtoken ""C"" IL_007b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0080: ldc.i4.2 IL_0081: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0086: dup IL_0087: ldc.i4.0 IL_0088: ldc.i4.0 IL_0089: ldnull IL_008a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008f: stelem.ref IL_0090: dup IL_0091: ldc.i4.1 IL_0092: ldc.i4.0 IL_0093: ldnull IL_0094: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0099: stelem.ref IL_009a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00a9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00ae: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00b8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_00bd: brtrue.s IL_00fd IL_00bf: ldc.i4.0 IL_00c0: ldtoken ""C"" IL_00c5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ca: ldc.i4.3 IL_00cb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d0: dup IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldnull IL_00d4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d9: stelem.ref IL_00da: dup IL_00db: ldc.i4.1 IL_00dc: ldc.i4.0 IL_00dd: ldnull IL_00de: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e3: stelem.ref IL_00e4: dup IL_00e5: ldc.i4.2 IL_00e6: ldc.i4.1 IL_00e7: ldnull IL_00e8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ed: stelem.ref IL_00ee: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_00fd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_0102: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_0107: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_010c: ldarg.1 IL_010d: ldarg.2 IL_010e: ldloc.0 IL_010f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_0114: ldarg.3 IL_0115: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_011a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object)"" IL_011f: ret } "); #endif } [Fact] public void CompoundStaticIndexerAssignment() { string source = @" public class C { public dynamic this[int a, object o] { get { return null; } set { } } public int f() { return 1; } public dynamic M(C c, dynamic v) { return c[f(), null] *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 111 (0x6f) .maxstack 11 .locals init (C V_0, int V_1, object V_2) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: call ""int C.f()"" IL_0008: stloc.1 IL_0009: ldloc.0 IL_000a: ldloc.1 IL_000b: ldnull IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0011: brtrue.s IL_0049 IL_0013: ldc.i4.0 IL_0014: ldc.i4.s 69 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0058: ldloc.0 IL_0059: ldloc.1 IL_005a: ldnull IL_005b: callvirt ""dynamic C.this[int, object].get"" IL_0060: ldarg.2 IL_0061: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0066: dup IL_0067: stloc.2 IL_0068: callvirt ""void C.this[int, object].set"" IL_006d: ldloc.2 IL_006e: ret }"); #if TODO // locals and parameters shouldn't be spilled @" { // Code size 109 (0x6d) .maxstack 11 .locals init (int V_0, object V_1) IL_0000: ldarg.0 IL_0001: call ""int C.f()"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldloc.0 IL_0009: ldnull IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_000f: brtrue.s IL_0047 IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 69 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0056: ldarg.1 IL_0057: ldloc.0 IL_0058: ldnull IL_0059: callvirt ""dynamic C.this[int, object].get"" IL_005e: ldarg.2 IL_005f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0064: dup IL_0065: stloc.1 IL_0066: callvirt ""void C.this[int, object].set"" IL_006b: ldloc.1 IL_006c: ret } "); #endif } [Fact] public void CompoundDynamicIndexerAssignment_ByRef() { string source = @" public class C { public dynamic Field; public C c; public C f() { return this; } public dynamic M(dynamic d, dynamic v) { int[] b = null; return d[ref f().Field, out b[10], c.c] *= v; } }"; // Dev11 emits different (unverifiable) code CompileAndVerifyIL(source, "C.M", @" { // Code size 342 (0x156) .maxstack 15 .locals init (object V_0, object& V_1, int& V_2, C V_3) IL_0000: ldnull IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: call ""C C.f()"" IL_0009: ldflda ""dynamic C.Field"" IL_000e: stloc.1 IL_000f: ldc.i4.s 10 IL_0011: ldelema ""int"" IL_0016: stloc.2 IL_0017: ldarg.0 IL_0018: ldfld ""C C.c"" IL_001d: ldfld ""C C.c"" IL_0022: stloc.3 IL_0023: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0028: brtrue.s IL_0082 IL_002a: ldc.i4 0x80 IL_002f: ldtoken ""C"" IL_0034: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0039: ldc.i4.5 IL_003a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003f: dup IL_0040: ldc.i4.0 IL_0041: ldc.i4.0 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.s 9 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.2 IL_0056: ldc.i4.s 17 IL_0058: ldnull IL_0059: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005e: stelem.ref IL_005f: dup IL_0060: ldc.i4.3 IL_0061: ldc.i4.1 IL_0062: ldnull IL_0063: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0068: stelem.ref IL_0069: dup IL_006a: ldc.i4.4 IL_006b: ldc.i4.0 IL_006c: ldnull IL_006d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0072: stelem.ref IL_0073: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0078: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007d: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0082: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0087: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>>.Target"" IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0091: ldloc.0 IL_0092: ldloc.1 IL_0093: ldloc.2 IL_0094: ldloc.3 IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_009a: brtrue.s IL_00d2 IL_009c: ldc.i4.0 IL_009d: ldc.i4.s 69 IL_009f: ldtoken ""C"" IL_00a4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a9: ldc.i4.2 IL_00aa: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00af: dup IL_00b0: ldc.i4.0 IL_00b1: ldc.i4.0 IL_00b2: ldnull IL_00b3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b8: stelem.ref IL_00b9: dup IL_00ba: ldc.i4.1 IL_00bb: ldc.i4.0 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cd: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00d7: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00e1: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_00e6: brtrue.s IL_0132 IL_00e8: ldc.i4.0 IL_00e9: ldtoken ""C"" IL_00ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00f3: ldc.i4.4 IL_00f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00f9: dup IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.0 IL_00fc: ldnull IL_00fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0102: stelem.ref IL_0103: dup IL_0104: ldc.i4.1 IL_0105: ldc.i4.s 9 IL_0107: ldnull IL_0108: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010d: stelem.ref IL_010e: dup IL_010f: ldc.i4.2 IL_0110: ldc.i4.s 17 IL_0112: ldnull IL_0113: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0118: stelem.ref IL_0119: dup IL_011a: ldc.i4.3 IL_011b: ldc.i4.1 IL_011c: ldnull IL_011d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0122: stelem.ref IL_0123: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0128: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012d: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0132: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0137: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>>.Target"" IL_013c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0141: ldloc.0 IL_0142: ldloc.1 IL_0143: ldloc.2 IL_0144: ldloc.3 IL_0145: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref int, C)"" IL_014a: ldarg.2 IL_014b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0150: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref int, C, object)"" IL_0155: ret }"); } [Fact] public void CompoundDynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static string s; static void M() { d[0] += s; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 99 (0x63) .maxstack 10 .locals init (object[] V_0) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 63 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.1 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, string, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_0054: ldloc.0 IL_0055: ldc.i4.0 IL_0056: ldelem.ref IL_0057: ldsfld ""string C.s"" IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, string)"" IL_0061: stelem.ref IL_0062: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToStruct() { string source = @" class C { dynamic d = null; public void M() { bool ret = true; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 238 (0xee) .maxstack 13 .locals init (bool V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_0007: brtrue.s IL_002e IL_0009: ldc.i4.s 16 IL_000b: ldtoken ""bool"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0024: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0029: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_002e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_0033: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_0042: brtrue.s IL_007a IL_0044: ldc.i4.0 IL_0045: ldc.i4.s 64 IL_0047: ldtoken ""C"" IL_004c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0051: ldc.i4.2 IL_0052: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0057: dup IL_0058: ldc.i4.0 IL_0059: ldc.i4.1 IL_005a: ldnull IL_005b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0060: stelem.ref IL_0061: dup IL_0062: ldc.i4.1 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_0089: ldloc.0 IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008f: brtrue.s IL_00c7 IL_0091: ldc.i4.0 IL_0092: ldc.i4.s 13 IL_0094: ldtoken ""C"" IL_0099: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009e: ldc.i4.2 IL_009f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a4: dup IL_00a5: ldc.i4.0 IL_00a6: ldc.i4.3 IL_00a7: ldnull IL_00a8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ad: stelem.ref IL_00ae: dup IL_00af: ldc.i4.1 IL_00b0: ldc.i4.0 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00c7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00cc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldc.i4.1 IL_00d7: ldarg.0 IL_00d8: ldfld ""dynamic C.d"" IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00e2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_00e7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ec: stloc.0 IL_00ed: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToClass() { string source = @" class C { dynamic d = null; public void M() { C ret = null; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 238 (0xee) .maxstack 13 .locals init (C V_0) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_0007: brtrue.s IL_002e IL_0009: ldc.i4.s 16 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0024: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0029: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_002e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_0033: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_0042: brtrue.s IL_007a IL_0044: ldc.i4.0 IL_0045: ldc.i4.s 64 IL_0047: ldtoken ""C"" IL_004c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0051: ldc.i4.2 IL_0052: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0057: dup IL_0058: ldc.i4.0 IL_0059: ldc.i4.1 IL_005a: ldnull IL_005b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0060: stelem.ref IL_0061: dup IL_0062: ldc.i4.1 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_0089: ldloc.0 IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008f: brtrue.s IL_00c7 IL_0091: ldc.i4.0 IL_0092: ldc.i4.s 13 IL_0094: ldtoken ""C"" IL_0099: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009e: ldc.i4.2 IL_009f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a4: dup IL_00a5: ldc.i4.0 IL_00a6: ldc.i4.3 IL_00a7: ldnull IL_00a8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ad: stelem.ref IL_00ae: dup IL_00af: ldc.i4.1 IL_00b0: ldc.i4.0 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00c7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00cc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldc.i4.1 IL_00d7: ldarg.0 IL_00d8: ldfld ""dynamic C.d"" IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00e2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_00e7: callvirt ""C System.Func<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ec: stloc.0 IL_00ed: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToPointer() { string source = @" class C { dynamic d = null; public unsafe void M() { int* ret = null; ret &= (1 == d); } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,3): error CS0019: Operator '&=' cannot be applied to operands of type 'int*' and 'dynamic' Diagnostic(ErrorCode.ERR_BadBinaryOps, "ret &= (1 == d)").WithArguments("&=", "int*", "dynamic")); } [Fact] public void CompoundAssignment_WithNoDynamicConversion_Object() { string source = @" class C { dynamic d = null; public void M() { object ret = null; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 174 (0xae) .maxstack 11 .locals init (object V_0) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0007: brtrue.s IL_003f IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 64 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.2 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0035: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0044: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_004e: ldloc.0 IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_0054: brtrue.s IL_008c IL_0056: ldc.i4.0 IL_0057: ldc.i4.s 13 IL_0059: ldtoken ""C"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: ldc.i4.2 IL_0064: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0069: dup IL_006a: ldc.i4.0 IL_006b: ldc.i4.3 IL_006c: ldnull IL_006d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0072: stelem.ref IL_0073: dup IL_0074: ldc.i4.1 IL_0075: ldc.i4.0 IL_0076: ldnull IL_0077: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007c: stelem.ref IL_007d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0082: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0087: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_0091: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_0096: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_009b: ldc.i4.1 IL_009c: ldarg.0 IL_009d: ldfld ""dynamic C.d"" IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00a7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00ac: stloc.0 IL_00ad: ret } "); } [Fact] public void CompoundAssignment_UserDefinedOperator() { string source = @" class C { public static dynamic operator +(C lhs, int rhs) { return null; } static void M() { C c = new C(); c += 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 4 .locals init (C V_0) //c IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_000b: brtrue.s IL_0031 IL_000d: ldc.i4.0 IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: call ""dynamic C.op_Addition(C, int)"" IL_0047: callvirt ""C System.Func<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004c: stloc.0 IL_004d: ret } "); } [Fact] public void CompoundAssignment_Result() { string source = @" class C { bool a = true; bool b = true; dynamic d = null; int M() { if ((a &= d) != b) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 11 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""bool"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0041: brtrue.s IL_0079 IL_0043: ldc.i4.0 IL_0044: ldc.i4.s 64 IL_0046: ldtoken ""C"" IL_004b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0050: ldc.i4.2 IL_0051: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0056: dup IL_0057: ldc.i4.0 IL_0058: ldc.i4.1 IL_0059: ldnull IL_005a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005f: stelem.ref IL_0060: dup IL_0061: ldc.i4.1 IL_0062: ldc.i4.0 IL_0063: ldnull IL_0064: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0069: stelem.ref IL_006a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0074: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0079: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_007e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0083: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0088: ldarg.0 IL_0089: ldfld ""bool C.a"" IL_008e: ldarg.0 IL_008f: ldfld ""dynamic C.d"" IL_0094: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0099: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009e: dup IL_009f: stloc.0 IL_00a0: stfld ""bool C.a"" IL_00a5: ldloc.0 IL_00a6: ldarg.0 IL_00a7: ldfld ""bool C.b"" IL_00ac: beq.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret }"); } [Fact] public void CompoundAssignment_Nullable() { string source = @" class C { int M() { bool? b = true; dynamic d = null; if ((d &= null) != (b &= null)) { return 1; } return 2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 278 (0x116) .maxstack 12 .locals init (bool? V_0, //b object V_1, //d bool? V_2, bool? V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""bool?..ctor(bool)"" IL_0008: ldnull IL_0009: stloc.1 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_000f: brtrue.s IL_003d IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 83 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0051: brtrue.s IL_0089 IL_0053: ldc.i4.0 IL_0054: ldc.i4.s 35 IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.2 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: dup IL_0071: ldc.i4.1 IL_0072: ldc.i4.1 IL_0073: ldnull IL_0074: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0079: stelem.ref IL_007a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0084: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_008e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>>.Target"" IL_0093: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_009d: brtrue.s IL_00d5 IL_009f: ldc.i4.0 IL_00a0: ldc.i4.s 64 IL_00a2: ldtoken ""C"" IL_00a7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ac: ldc.i4.2 IL_00ad: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b2: dup IL_00b3: ldc.i4.0 IL_00b4: ldc.i4.0 IL_00b5: ldnull IL_00b6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bb: stelem.ref IL_00bc: dup IL_00bd: ldc.i4.1 IL_00be: ldc.i4.2 IL_00bf: ldnull IL_00c0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c5: stelem.ref IL_00c6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00da: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00df: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00e4: ldloc.1 IL_00e5: ldnull IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00eb: dup IL_00ec: stloc.1 IL_00ed: ldloc.0 IL_00ee: stloc.2 IL_00ef: ldloca.s V_2 IL_00f1: call ""bool bool?.GetValueOrDefault()"" IL_00f6: brtrue.s IL_00fb IL_00f8: ldloc.2 IL_00f9: br.s IL_0104 IL_00fb: ldloca.s V_3 IL_00fd: initobj ""bool?"" IL_0103: ldloc.3 IL_0104: dup IL_0105: stloc.0 IL_0106: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, bool?)"" IL_010b: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0110: brfalse.s IL_0114 IL_0112: ldc.i4.1 IL_0113: ret IL_0114: ldc.i4.2 IL_0115: ret } "); } [Fact] public void CompoundAssignment() { string source = @" class C { static void Main() { dynamic[] x = new string[] { ""hello"" }; x[0] += ""!""; System.Console.Write(x[0]); } } "; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "hello!", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef, SystemCoreRef }); comp.VerifyDiagnostics(); // No runtime failure (System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.) // because of the special handling for dynamic in LocalRewriter.TransformCompoundAssignmentLHS } #endregion #region Object And Collection Initializers [Fact] public void DynamicObjectInitializer_Level2() { string source = @" using System; class C { public dynamic A { get; set; } static void M() { var x = new C { A = { B = 1 } }; } } "; // Bug in Dev11: it boxes the constant literal (1) and the corresponding call-site parameter is typed to object. CompileAndVerifyIL(source, "C.M", @" { // Code size 99 (0x63) .maxstack 8 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_0046 IL_000d: ldc.i4.0 IL_000e: ldstr ""B"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.2 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.3 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_004b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_0055: ldloc.0 IL_0056: callvirt ""dynamic C.A.get"" IL_005b: ldc.i4.1 IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0061: pop IL_0062: ret }"); } /// <summary> /// We can shared dynamic sites for GetMembers of level n-1 on level n for n >= 3. /// </summary> [Fact] public void DynamicObjectInitializer_Level3() { string source = @" using System; class C { public dynamic A { get; set; } static void M() { var x = new C { A = { B = { P = 1, Q = 2 } } }; } } "; // Dev11 creates 4 call sites: GetMember[B] #1, SetMember[P], GetMember[B] #2, SetMember[Q] and calls them as follows: // var c = new C(); // SetMember[P](GetMember[B](c) #1, 1) // SetMember[Q](GetMember[B](c) #2, 2) // // To maintain runtime compatibility we have to invoke GetMember[B] twice, but we can reuse the call-site: // We create 3 call sites: GetMember[B] #1, SetMember[P], SetMember[Q] // var c = new C(); // SetMember[P](GetMember[B](c) #1, 1) // SetMember[Q](GetMember[B](c) #1, 2) // // We initialize all sites up-front so that we are able to avoid duplication of call-site initialization. // // Also Dev11 emits flags (None, None) for SetMember[P], while Roslyn emits (None, UseCompileTimeType | Constant) since the RHS is a constant. CompileAndVerifyIL(source, "C.M", @" { // Code size 285 (0x11d) .maxstack 8 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_003c IL_000d: ldc.i4.0 IL_000e: ldstr ""B"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.1 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_0041: brtrue.s IL_007c IL_0043: ldc.i4.0 IL_0044: ldstr ""P"" IL_0049: ldtoken ""C"" IL_004e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0053: ldc.i4.2 IL_0054: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0059: dup IL_005a: ldc.i4.0 IL_005b: ldc.i4.0 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.3 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_0081: brtrue.s IL_00bc IL_0083: ldc.i4.0 IL_0084: ldstr ""Q"" IL_0089: ldtoken ""C"" IL_008e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0093: ldc.i4.2 IL_0094: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0099: dup IL_009a: ldc.i4.0 IL_009b: ldc.i4.0 IL_009c: ldnull IL_009d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a2: stelem.ref IL_00a3: dup IL_00a4: ldc.i4.1 IL_00a5: ldc.i4.3 IL_00a6: ldnull IL_00a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ac: stelem.ref IL_00ad: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00b2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00b7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_00c1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_00cb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_00d0: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_00da: ldloc.0 IL_00db: callvirt ""dynamic C.A.get"" IL_00e0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e5: ldc.i4.1 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00eb: pop IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00f1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00f6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_0100: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_010a: ldloc.0 IL_010b: callvirt ""dynamic C.A.get"" IL_0110: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0115: ldc.i4.2 IL_0116: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_011b: pop IL_011c: ret } "); } [Fact] public void DynamicCollectionInitializer_DynamicReceiver_InStaticMethod() { string source = @" class C { public dynamic A { get; set; } static void M() { var x = new C { A = { { 1 } } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.3 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_005a: ldloc.0 IL_005b: callvirt ""dynamic C.A.get"" IL_0060: ldc.i4.1 IL_0061: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0066: ret } "); } [Fact] public void DynamicCollectionInitializer_DynamicReceiver_InInstanceMethod() { string source = @" class C { public dynamic A { get; set; } void M() { var x = new C { A = { { 1 } } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.3 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_005a: ldloc.0 IL_005b: callvirt ""dynamic C.A.get"" IL_0060: ldc.i4.1 IL_0061: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0066: ret } "); } [Fact] public void DynamicCollectionInitializer_StaticReceiver() { string source = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return null; } public void Add(int a) { } void M(dynamic d) { var x = new C { { d } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 98 (0x62) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.1 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, C, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_005a: ldloc.0 IL_005b: ldarg.1 IL_005c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_0061: ret } "); } [Fact] public void ObjectAndCollectionInitializer() { string source = @" using System; using System.Collections.Generic; class Program { static void Main() { var c = new C { X = { Y = { 1 } } }; } } class C { public dynamic X = new X(); } class X { public List<int> Y; } "; CompileAndVerifyIL(source, "Program.Main", @" { // Code size 177 (0xb1) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_000b: brtrue.s IL_003c IL_000d: ldc.i4.0 IL_000e: ldstr ""Y"" IL_0013: ldtoken ""Program"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.1 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0041: brtrue.s IL_0081 IL_0043: ldc.i4 0x100 IL_0048: ldstr ""Add"" IL_004d: ldnull IL_004e: ldtoken ""Program"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldc.i4.2 IL_0059: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005e: dup IL_005f: ldc.i4.0 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0086: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0090: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_0095: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_009f: ldloc.0 IL_00a0: ldfld ""dynamic C.X"" IL_00a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00aa: ldc.i4.1 IL_00ab: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00b0: ret } "); } #endregion #region Foreach [Fact] public void ForEach_StaticallyTypedVariable() { string source = @" class C { void M(dynamic d) { foreach (int x in d) { System.Console.WriteLine(x); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, System.IDisposable V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Collections.IEnumerable"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_0045: stloc.0 .try { IL_0046: br.s IL_0093 IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_004d: brtrue.s IL_0074 IL_004f: ldc.i4.s 16 IL_0051: ldtoken ""int"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldtoken ""C"" IL_0060: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0079: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0083: ldloc.0 IL_0084: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0089: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008e: call ""void System.Console.WriteLine(int)"" IL_0093: ldloc.0 IL_0094: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0099: brtrue.s IL_0048 IL_009b: leave.s IL_00ae } finally { IL_009d: ldloc.0 IL_009e: isinst ""System.IDisposable"" IL_00a3: stloc.1 IL_00a4: ldloc.1 IL_00a5: brfalse.s IL_00ad IL_00a7: ldloc.1 IL_00a8: callvirt ""void System.IDisposable.Dispose()"" IL_00ad: endfinally } IL_00ae: ret } "); } [Fact] public void ForEach_ImplicitlyTypedVariable() { string source = @" class C { void M(dynamic d) { foreach (var x in d) { System.Console.WriteLine(x); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 208 (0xd0) .maxstack 9 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.IDisposable V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Collections.IEnumerable"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_003a: ldarg.1 IL_003b: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_0045: stloc.0 .try { IL_0046: br.s IL_00b4 IL_0048: ldloc.0 IL_0049: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_004e: stloc.1 IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0054: brtrue.s IL_0095 IL_0056: ldc.i4 0x100 IL_005b: ldstr ""WriteLine"" IL_0060: ldnull IL_0061: ldtoken ""C"" IL_0066: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006b: ldc.i4.2 IL_006c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0071: dup IL_0072: ldc.i4.0 IL_0073: ldc.i4.s 33 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.1 IL_007e: ldc.i4.0 IL_007f: ldnull IL_0080: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0085: stelem.ref IL_0086: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_008b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0090: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_009a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_00a4: ldtoken ""System.Console"" IL_00a9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ae: ldloc.1 IL_00af: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_00b4: ldloc.0 IL_00b5: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00ba: brtrue.s IL_0048 IL_00bc: leave.s IL_00cf } finally { IL_00be: ldloc.0 IL_00bf: isinst ""System.IDisposable"" IL_00c4: stloc.2 IL_00c5: ldloc.2 IL_00c6: brfalse.s IL_00ce IL_00c8: ldloc.2 IL_00c9: callvirt ""void System.IDisposable.Dispose()"" IL_00ce: endfinally } IL_00cf: ret }"); } [WorkItem(2720, "https://github.com/dotnet/roslyn/issues/2720")] [Fact] public void ContextTypeInAsyncLambda() { string source = @" using System; using System.Threading.Tasks; class C { static void Main() { dynamic d = Task.FromResult(""a""); G(async () => await d()); } static void G(Func<Task<object>> f) { } }"; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0.<<Main>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 537 (0x219) .maxstack 10 .locals init (int V_0, C.<>c__DisplayClass0_0 V_1, object V_2, object V_3, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4, System.Runtime.CompilerServices.INotifyCompletion V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_0.<<Main>b__0>d.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse IL_0185 IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_005f: brtrue.s IL_008b IL_0061: ldc.i4.0 IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.0 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_009a: ldloc.1 IL_009b: ldfld ""dynamic C.<>c__DisplayClass0_0.d"" IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00aa: stloc.3 IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00b0: brtrue.s IL_00d7 IL_00b2: ldc.i4.s 16 IL_00b4: ldtoken ""bool"" IL_00b9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00be: ldtoken ""C"" IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00cd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00dc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_00e1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_00eb: brtrue.s IL_011c IL_00ed: ldc.i4.0 IL_00ee: ldstr ""IsCompleted"" IL_00f3: ldtoken ""C"" IL_00f8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00fd: ldc.i4.1 IL_00fe: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0103: dup IL_0104: ldc.i4.0 IL_0105: ldc.i4.0 IL_0106: ldnull IL_0107: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010c: stelem.ref IL_010d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0112: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0117: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_011c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_0121: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0126: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_012b: ldloc.3 IL_012c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0131: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0136: brtrue.s IL_019c IL_0138: ldarg.0 IL_0139: ldc.i4.0 IL_013a: dup IL_013b: stloc.0 IL_013c: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_0141: ldarg.0 IL_0142: ldloc.3 IL_0143: stfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_0148: ldloc.3 IL_0149: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_014e: stloc.s V_4 IL_0150: ldloc.s V_4 IL_0152: brtrue.s IL_016f IL_0154: ldloc.3 IL_0155: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015a: stloc.s V_5 IL_015c: ldarg.0 IL_015d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0162: ldloca.s V_5 IL_0164: ldarg.0 IL_0165: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<>c__DisplayClass0_0.<<Main>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<>c__DisplayClass0_0.<<Main>b__0>d)"" IL_016a: ldnull IL_016b: stloc.s V_5 IL_016d: br.s IL_017d IL_016f: ldarg.0 IL_0170: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0175: ldloca.s V_4 IL_0177: ldarg.0 IL_0178: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<>c__DisplayClass0_0.<<Main>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<>c__DisplayClass0_0.<<Main>b__0>d)"" IL_017d: ldnull IL_017e: stloc.s V_4 IL_0180: leave IL_0218 IL_0185: ldarg.0 IL_0186: ldfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_018b: stloc.3 IL_018c: ldarg.0 IL_018d: ldnull IL_018e: stfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_0193: ldarg.0 IL_0194: ldc.i4.m1 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_019c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01a1: brtrue.s IL_01d3 IL_01a3: ldc.i4.0 IL_01a4: ldstr ""GetResult"" IL_01a9: ldnull IL_01aa: ldtoken ""C"" IL_01af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b4: ldc.i4.1 IL_01b5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ba: dup IL_01bb: ldc.i4.0 IL_01bc: ldc.i4.0 IL_01bd: ldnull IL_01be: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c3: stelem.ref IL_01c4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01ce: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01d8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01e2: ldloc.3 IL_01e3: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01e8: stloc.2 IL_01e9: leave.s IL_0204 } catch System.Exception { IL_01eb: stloc.s V_6 IL_01ed: ldarg.0 IL_01ee: ldc.i4.s -2 IL_01f0: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_01f5: ldarg.0 IL_01f6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_01fb: ldloc.s V_6 IL_01fd: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0202: leave.s IL_0218 } IL_0204: ldarg.0 IL_0205: ldc.i4.s -2 IL_0207: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_020c: ldarg.0 IL_020d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0212: ldloc.2 IL_0213: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_0218: ret }"); } [WorkItem(5323, "https://github.com/dotnet/roslyn/issues/5323")] [Fact] public void DynamicUsingWithYield1() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class Program { static void Main(string[] args) { foreach(var i in Iter()) { System.Console.WriteLine(i); } } static IEnumerable<Task> Iter() { dynamic d = 123; using (var t = D(d)) { yield return t; t.Wait(); } } static Task D(dynamic arg) { return Task.FromResult(1); } }"; var comp = CreateCompilationWithCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); } [WorkItem(5323, "https://github.com/dotnet/roslyn/issues/5323")] [Fact] public void DynamicUsingWithYield2() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class Program { static void Main(string[] args) { foreach(var i in Iter()) { System.Console.WriteLine(i); } } static IEnumerable<Task> Iter() { dynamic d = 123; var t = D(d); using (t) { yield return t; t.Wait(); } } static Task D(dynamic arg) { return Task.FromResult(1); } }"; var comp = CreateCompilationWithCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); } #endregion #region Using [Fact] public void UsingStatement() { string source = @" using System; class C { dynamic d = null; void M() { using (dynamic u = d) { Console.WriteLine(); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (object V_0, //u System.IDisposable V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_000c: brtrue.s IL_0032 IL_000e: ldc.i4.0 IL_000f: ldtoken ""System.IDisposable"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldtoken ""C"" IL_001e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0023: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0028: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0032: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0037: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>>.Target"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0041: ldloc.0 IL_0042: callvirt ""System.IDisposable System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0047: stloc.1 .try { IL_0048: call ""void System.Console.WriteLine()"" IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.1 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.1 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } #endregion #region Async [Fact] public void AwaitAwait() { string source = @" using System; using System.Threading.Tasks; class C { static dynamic d; static async void M() { var x = await await d; } }"; CompileAndVerifyIL(source, "C.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 855 (0x357) .maxstack 10 .locals init (int V_0, object V_1, object V_2, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_3, System.Runtime.CompilerServices.INotifyCompletion V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_013c IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: beq IL_02c4 IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_005a: ldsfld ""dynamic C.d"" IL_005f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0064: stloc.2 IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_006a: brtrue.s IL_0091 IL_006c: ldc.i4.s 16 IL_006e: ldtoken ""bool"" IL_0073: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0078: ldtoken ""C"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00a5: brtrue.s IL_00d6 IL_00a7: ldc.i4.0 IL_00a8: ldstr ""IsCompleted"" IL_00ad: ldtoken ""C"" IL_00b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b7: ldc.i4.1 IL_00b8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bd: dup IL_00be: ldc.i4.0 IL_00bf: ldc.i4.0 IL_00c0: ldnull IL_00c1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c6: stelem.ref IL_00c7: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cc: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d1: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00db: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00e5: ldloc.2 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00eb: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00f0: brtrue.s IL_0153 IL_00f2: ldarg.0 IL_00f3: ldc.i4.0 IL_00f4: dup IL_00f5: stloc.0 IL_00f6: stfld ""int C.<M>d__1.<>1__state"" IL_00fb: ldarg.0 IL_00fc: ldloc.2 IL_00fd: stfld ""object C.<M>d__1.<>u__1"" IL_0102: ldloc.2 IL_0103: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0108: stloc.3 IL_0109: ldloc.3 IL_010a: brtrue.s IL_0127 IL_010c: ldloc.2 IL_010d: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_0112: stloc.s V_4 IL_0114: ldarg.0 IL_0115: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_011a: ldloca.s V_4 IL_011c: ldarg.0 IL_011d: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<M>d__1)"" IL_0122: ldnull IL_0123: stloc.s V_4 IL_0125: br.s IL_0135 IL_0127: ldarg.0 IL_0128: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_012d: ldloca.s V_3 IL_012f: ldarg.0 IL_0130: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<M>d__1)"" IL_0135: ldnull IL_0136: stloc.3 IL_0137: leave IL_0356 IL_013c: ldarg.0 IL_013d: ldfld ""object C.<M>d__1.<>u__1"" IL_0142: stloc.2 IL_0143: ldarg.0 IL_0144: ldnull IL_0145: stfld ""object C.<M>d__1.<>u__1"" IL_014a: ldarg.0 IL_014b: ldc.i4.m1 IL_014c: dup IL_014d: stloc.0 IL_014e: stfld ""int C.<M>d__1.<>1__state"" IL_0153: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_0158: brtrue.s IL_018a IL_015a: ldc.i4.0 IL_015b: ldstr ""GetResult"" IL_0160: ldnull IL_0161: ldtoken ""C"" IL_0166: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_016b: ldc.i4.1 IL_016c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0171: dup IL_0172: ldc.i4.0 IL_0173: ldc.i4.0 IL_0174: ldnull IL_0175: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_017a: stelem.ref IL_017b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0180: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0185: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_018a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_018f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0194: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_0199: ldloc.2 IL_019a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_019f: stloc.1 IL_01a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01a5: brtrue.s IL_01d7 IL_01a7: ldc.i4.0 IL_01a8: ldstr ""GetAwaiter"" IL_01ad: ldnull IL_01ae: ldtoken ""C"" IL_01b3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b8: ldc.i4.1 IL_01b9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01be: dup IL_01bf: ldc.i4.0 IL_01c0: ldc.i4.0 IL_01c1: ldnull IL_01c2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c7: stelem.ref IL_01c8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01cd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01d2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01dc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01e1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01e6: ldloc.1 IL_01e7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01ec: stloc.2 IL_01ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_01f2: brtrue.s IL_0219 IL_01f4: ldc.i4.s 16 IL_01f6: ldtoken ""bool"" IL_01fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0200: ldtoken ""C"" IL_0205: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_020a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_020f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0214: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_0219: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_021e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0223: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_0228: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_022d: brtrue.s IL_025e IL_022f: ldc.i4.0 IL_0230: ldstr ""IsCompleted"" IL_0235: ldtoken ""C"" IL_023a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_023f: ldc.i4.1 IL_0240: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0245: dup IL_0246: ldc.i4.0 IL_0247: ldc.i4.0 IL_0248: ldnull IL_0249: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_024e: stelem.ref IL_024f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0254: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0259: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_025e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_0263: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0268: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_026d: ldloc.2 IL_026e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0273: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0278: brtrue.s IL_02db IL_027a: ldarg.0 IL_027b: ldc.i4.1 IL_027c: dup IL_027d: stloc.0 IL_027e: stfld ""int C.<M>d__1.<>1__state"" IL_0283: ldarg.0 IL_0284: ldloc.2 IL_0285: stfld ""object C.<M>d__1.<>u__1"" IL_028a: ldloc.2 IL_028b: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0290: stloc.3 IL_0291: ldloc.3 IL_0292: brtrue.s IL_02af IL_0294: ldloc.2 IL_0295: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_029a: stloc.s V_4 IL_029c: ldarg.0 IL_029d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_02a2: ldloca.s V_4 IL_02a4: ldarg.0 IL_02a5: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<M>d__1)"" IL_02aa: ldnull IL_02ab: stloc.s V_4 IL_02ad: br.s IL_02bd IL_02af: ldarg.0 IL_02b0: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_02b5: ldloca.s V_3 IL_02b7: ldarg.0 IL_02b8: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<M>d__1)"" IL_02bd: ldnull IL_02be: stloc.3 IL_02bf: leave IL_0356 IL_02c4: ldarg.0 IL_02c5: ldfld ""object C.<M>d__1.<>u__1"" IL_02ca: stloc.2 IL_02cb: ldarg.0 IL_02cc: ldnull IL_02cd: stfld ""object C.<M>d__1.<>u__1"" IL_02d2: ldarg.0 IL_02d3: ldc.i4.m1 IL_02d4: dup IL_02d5: stloc.0 IL_02d6: stfld ""int C.<M>d__1.<>1__state"" IL_02db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_02e0: brtrue.s IL_0312 IL_02e2: ldc.i4.0 IL_02e3: ldstr ""GetResult"" IL_02e8: ldnull IL_02e9: ldtoken ""C"" IL_02ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02f3: ldc.i4.1 IL_02f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_02f9: dup IL_02fa: ldc.i4.0 IL_02fb: ldc.i4.0 IL_02fc: ldnull IL_02fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0302: stelem.ref IL_0303: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0308: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_030d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0312: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0317: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_031c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0321: ldloc.2 IL_0322: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0327: pop IL_0328: leave.s IL_0343 } catch System.Exception { IL_032a: stloc.s V_5 IL_032c: ldarg.0 IL_032d: ldc.i4.s -2 IL_032f: stfld ""int C.<M>d__1.<>1__state"" IL_0334: ldarg.0 IL_0335: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_033a: ldloc.s V_5 IL_033c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0341: leave.s IL_0356 } IL_0343: ldarg.0 IL_0344: ldc.i4.s -2 IL_0346: stfld ""int C.<M>d__1.<>1__state"" IL_034b: ldarg.0 IL_034c: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_0351: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0356: ret } "); } [Fact] public void MissingCSharpArgumentInfoCreate() { string source = @"class C { static void F(dynamic d) { d.F(); } }"; var comp = CreateCompilationWithMscorlib45( new[] { DynamicAttributeSource, source }, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); comp.VerifyEmitDiagnostics( // (5,9): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // d.F(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(5, 9)); } [Fact] [WorkItem(377883, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377883")] public void MissingCSharpArgumentInfoCreate_Async() { string source = @"using System.Threading.Tasks; class C { static async Task F(dynamic d) { await d; } }"; var comp = CreateCompilationWithMscorlib45( new[] { DynamicAttributeSource, source }, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); comp.VerifyEmitDiagnostics( // (6,15): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // await d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(6, 15)); } #endregion #region Regression Tests [ConditionalFact(typeof(DesktopOnly))] public void ByRefDynamic() { string source = @" public class Program { static void Main(string[] args) { System.Console.Write(Test1()); System.Console.Write("" ""); System.Console.Write(x.Length); } static dynamic x = new C1(); static int Test1() { return M1(ref x.Length); } static dynamic M1(ref dynamic d) { d = 321; return d; } } class C1 { public int Length = 123; } "; var comp = CompileAndVerify(source, expectedOutput: "321 123", references: new[] { CSharpRef }); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction1() { var source = @" using System; class Program { public static void Main() { M(""""); void M<T>(T slot) { slot = (dynamic)default; Console.WriteLine(slot is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__0_0`1'<T> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T>> '<>p__0' } // end of class <>o__0_0`1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::'<Main>g__M|0_0'<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<Main>g__M|0_0'<T> ( !!T slot ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2064 // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>::Invoke(!0, !1) IL_0040: starg.s slot IL_0042: ldarg.0 IL_0043: box !!T IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<Main>g__M|0_0' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction2() { var source = @" using System; class Program { public static void Main() { M1<string, string>(""""); } public static void M1<T1, T2>(T1 a) { M2<T1, T2>(a); void M2<T3, T4>(T3 b) { M3<T3, T4>(b); void M3<T5, T6>(T5 c) { c = (dynamic)default; Console.WriteLine(c is null); } } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1_1`6'<T1, T2, T3, T4, T5, T6> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T5>> '<>p__0' } // end of class <>o__1_1`6 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::M1<string, string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig static void M1<T1, T2> ( !!T1 a ) cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M2|1_0'<!!T1, !!T2, !!T1, !!T2>(!!2) IL_0006: ret } // end of method Program::M1 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M1>g__M2|1_0'<T1, T2, T3, T4> ( !!T3 b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M3|1_1'<!!T1, !!T2, !!T3, !!T4, !!T3, !!T4>(!!4) IL_0006: ret } // end of method Program::'<M1>g__M2|1_0' .method assembly hidebysig static void '<M1>g__M3|1_1'<T1, T2, T3, T4, T5, T6> ( !!T5 c ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2074 // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T5 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>::Invoke(!0, !1) IL_0040: starg.s c IL_0042: ldarg.0 IL_0043: box !!T5 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<M1>g__M3|1_1' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction3() { var source = @" using System; class Program { public static void Main() { M1(""""); } public static void M1<T1>(T1 a) { M2(a); void M2(T1 b) { b = (dynamic)default; Console.WriteLine(b is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1`1'<T1> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T1>> '<>p__0' } // end of class <>o__1`1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::M1<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig static void M1<T1> ( !!T1 a ) cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M2|1_0'<!!T1>(!!0) IL_0006: ret } // end of method Program::M1 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M1>g__M2|1_0'<T1> ( !!T1 b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T1 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>::Invoke(!0, !1) IL_0040: starg.s b IL_0042: ldarg.0 IL_0043: box !!T1 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<M1>g__M2|1_0' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction4() { var source = @" using System; class Program { public static void Main() { M1(""""); void M1<T>(T a) { M2(a); void M2<T>(T b) { b = (dynamic)default; Console.WriteLine(b is null); } } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1_0`2'<T, T> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T>> '<>p__0' } // end of class <>o__1_0`2 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::'<Main>g__M1|0_0'<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<Main>g__M1|0_0'<T> ( !!T a ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<Main>g__M2|0_1'<!!T, !!T>(!!1) IL_0006: ret } // end of method Program::'<Main>g__M1|0_0' .method assembly hidebysig static void '<Main>g__M2|0_1'<T, T> ( !!T b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>::Invoke(!0, !1) IL_0040: starg.s b IL_0042: ldarg.0 IL_0043: box !!T IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<Main>g__M2|0_1' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction5() { var source = @" using System; class Program { public static void Main() { Class<int>.M(); } } class Class<T1> { public static void M() { M1(""""); void M1<T2>(T2 a) { a = (dynamic)default; Console.WriteLine(a is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Class`1", @" .class private auto ansi beforefieldinit Class`1<T1> extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__0_0`1'<T1, T2> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T2>> '<>p__0' } // end of class <>o__0_0`1 // Methods .method public hidebysig static void M () cil managed { // Method begins at RVA 0x205f // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr """" IL_0005: call void class Class`1<!T1>::'<M>g__M1|0_0'<string>(!!0) IL_000a: ret } // end of method Class`1::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2057 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Class`1::.ctor .method assembly hidebysig static void '<M>g__M1|0_0'<T2> ( !!T2 a ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T2 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken class Class`1<!T1> IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>::Invoke(!0, !1) IL_0040: starg.s a IL_0042: ldarg.0 IL_0043: box !!T2 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Class`1::'<M>g__M1|0_0' } // end of class Class`1"); } private static void VerifyTypeIL(CompilationVerifier compilation, string typeName, string expected) { // .Net Core has different assemblies for the same standard library types as .Net Framework, meaning that that the emitted output will be different to the expected if we run them .Net Framework // Since we do not expect there to be any meaningful differences between output for .Net Core and .Net Framework, we will skip these tests on .Net Framework if (ExecutionConditionUtil.IsCoreClr) { compilation.VerifyTypeIL(typeName, expected); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGen_DynamicTests : CSharpTestBase { #region Helpers private CompilationVerifier CompileAndVerifyIL( string source, string methodName, string expectedOptimizedIL = null, string expectedUnoptimizedIL = null, MetadataReference[] references = null, bool allowUnsafe = false, [CallerFilePath] string callerPath = null, [CallerLineNumber] int callerLine = 0, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes) { references = references ?? new[] { SystemCoreRef, CSharpRef }; // verify that we emit correct optimized and unoptimized IL: var unoptimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe)); var optimizedCompilation = CreateCompilationWithMscorlib45(source, references, parseOptions: parseOptions, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All).WithAllowUnsafe(allowUnsafe)); var unoptimizedVerifier = CompileAndVerify(unoptimizedCompilation, verify: verify); var optimizedVerifier = CompileAndVerify(optimizedCompilation, verify: verify); // check what IL we emit exactly: if (expectedUnoptimizedIL != null) { unoptimizedVerifier.VerifyIL(methodName, expectedUnoptimizedIL, realIL: true, sequencePoints: methodName, callerPath: callerPath, callerLine: callerLine); } if (expectedOptimizedIL != null) { optimizedVerifier.VerifyIL(methodName, expectedOptimizedIL, realIL: true, callerPath: callerPath, callerLine: callerLine); } // return null if ambiguous return (expectedUnoptimizedIL != null) ^ (expectedOptimizedIL != null) ? (unoptimizedVerifier ?? optimizedVerifier) : null; } private readonly CSharpParseOptions _localFunctionParseOptions = TestOptions.Regular; #endregion #region C# Runtime and System.Core sources private const string CSharpBinderTemplate = @" using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Microsoft.CSharp.RuntimeBinder {{ {0} }} "; private const string CSharpBinderFlagsSource = @" public enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256 } "; private const string CSharpArgumentInfoFlagsSource = @" public enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32 } "; private const string CSharpArgumentInfoSource = @" public sealed class CSharpArgumentInfo { public static CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name) { return null; } } "; private readonly string[] _binderFactoriesSource = new[] { "CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context)", "CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context)", "CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", "CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)", }; private MetadataReference MakeCSharpRuntime(string excludeBinder = null, bool excludeBinderFlags = false, bool excludeArgumentInfoFlags = false, MetadataReference systemCore = null) { var sb = new StringBuilder(); sb.AppendLine(excludeBinderFlags ? "public enum CSharpBinderFlags { A }" : CSharpBinderFlagsSource); sb.AppendLine(excludeArgumentInfoFlags ? "public enum CSharpArgumentInfoFlags { A }" : CSharpArgumentInfoFlagsSource); sb.AppendLine(CSharpArgumentInfoSource); foreach (var src in excludeBinder == null ? _binderFactoriesSource : _binderFactoriesSource.Where(src => src.IndexOf(excludeBinder, StringComparison.Ordinal) == -1)) { sb.AppendFormat("public partial class Binder {{ public static {0} {{ return null; }} }}", src); sb.AppendLine(); } string source = string.Format(CSharpBinderTemplate, sb.ToString()); return CreateCompilationWithMscorlib40(source, new[] { systemCore ?? SystemCoreRef }, assemblyName: GetUniqueName()).EmitToImageReference(); } private const string ExpressionTypeSource = @" namespace System.Linq.Expressions { public enum ExpressionType { Add, AddChecked, And, AndAlso, ArrayLength, ArrayIndex, Call, Coalesce, Conditional, Constant, Convert, ConvertChecked, Divide, Equal, ExclusiveOr, GreaterThan, GreaterThanOrEqual, Invoke, Lambda, LeftShift, LessThan, LessThanOrEqual, ListInit, MemberAccess, MemberInit, Modulo, Multiply, MultiplyChecked, Negate, UnaryPlus, NegateChecked, New, NewArrayInit, NewArrayBounds, Not, NotEqual, Or, OrElse, Parameter, Power, Quote, RightShift, Subtract, SubtractChecked, TypeAs, TypeIs, Assign, Block, DebugInfo, Decrement, Dynamic, Default, Extension, Goto, Increment, Index, Label, RuntimeVariables, Loop, Switch, Throw, Try, Unbox, AddAssign, AndAssign, DivideAssign, ExclusiveOrAssign, LeftShiftAssign, ModuloAssign, MultiplyAssign, OrAssign, PowerAssign, RightShiftAssign, SubtractAssign, AddAssignChecked, MultiplyAssignChecked, SubtractAssignChecked, PreIncrementAssign, PreDecrementAssign, PostIncrementAssign, PostDecrementAssign, TypeEqual, OnesComplement, IsTrue, IsFalse } } "; private const string DynamicAttributeSource = @" namespace System.Runtime.CompilerServices { public sealed class DynamicAttribute : Attribute { public DynamicAttribute() { } public DynamicAttribute(bool[] transformFlags) { } } }"; private const string CallSiteSource = @" namespace System.Runtime.CompilerServices { public class CallSite { } public class CallSite<T> : CallSite where T : class { public T Target; public static CallSite<T> Create(CallSiteBinder binder) { return null; } } public abstract class CallSiteBinder { } }"; private const string SystemCoreSource = ExpressionTypeSource + DynamicAttributeSource + CallSiteSource; #endregion #region Missing Well-Known Members [Fact] public void Missing_CSharpArgumentInfo() { string source = @" class C { public event System.Action e; public C(dynamic d) { } void F(dynamic d) { var a1 = d * d; var a2 = (int)d; var a3 = d[d]; var a4 = d.M; var a5 = d(); var a6 = d.M(); var a7 = new C(d); e += d; var a9 = d[d] = d; var a10 = d.M = d; var a11 = -d; e(); } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics( // (9,18): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // var a1 = d * d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(9, 18) ); } [Fact] public void Missing_Binder() { var csrtRef = MakeCSharpRuntime(excludeBinder: "InvokeConstructor"); string source = @" class C { public C(int a) { } void F(dynamic d) { new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M)); } } "; CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (8,9): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor' // new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M)); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new C(d.M(d.M = d[-d], d[(int)d()] = d * d.M))").WithArguments("Microsoft.CSharp.RuntimeBinder.Binder", "InvokeConstructor") ); } [Fact] public void Missing_Flags() { var csrtRef = MakeCSharpRuntime(excludeBinderFlags: true, excludeArgumentInfoFlags: true); string source = @" class C { public static void G(int a) { } void F(dynamic d) { G(d); // CSharpBinderFlags.InvokeSimpleName, CSharpBinderFlags.ResultDiscarded // CSharpArgumentInfoFlags.None, CSharpArgumentInfoFlags.UseCompileTimeType } } "; // the compiler ignores the enum values, uses hardcoded values: CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef, csrtRef }).VerifyEmitDiagnostics(); } [Fact] public void Missing_Func() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // the delegate is generated, no error is reported CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }); } [Fact] public void InvalidFunc_Arity() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); var funcRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Invalid.InvalidFuncDelegateName.AsImmutableOrNull()); string source = @" class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // the delegate is generated, no error is reported var c = CompileAndVerifyWithMscorlib40(source, new[] { systemCoreRef, csrtRef, funcRef }); Assert.Equal(1, ((CSharpCompilation)c.Compilation).GlobalNamespace.GetMember<NamespaceSymbol>("System").GetMember<NamedTypeSymbol>("Func`13").Arity); } [Fact, WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")] public void InvalidFunc_Constraints() { var systemCoreRef = CreateCompilationWithMscorlib40(SystemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" namespace System { public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12) where T4 : class; } class C { dynamic F(dynamic d) { return d(1,2,3,4,5,6,7,8,9,10); // Func`13 } } "; // Desired: the delegate is generated, no error is reported. // Actual: use the malformed Func`13 time and failed to PEVerify. Not presently worthwhile to fix. CompileAndVerifyWithMscorlib40(source, new[] { systemCoreRef, csrtRef }, verify: Verification.Fails).VerifyIL("C.F", @" { // Code size 189 (0xbd) .maxstack 13 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_009b IL_000a: ldc.i4.0 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldc.i4.s 11 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.3 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.4 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.5 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.6 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.7 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.8 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.s 9 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.s 10 IL_0084: ldc.i4.3 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0091: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0096: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_00a0: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>>.Target"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>> C.<>o__0.<>p__0"" IL_00aa: ldarg.1 IL_00ab: ldc.i4.1 IL_00ac: ldc.i4.2 IL_00ad: ldc.i4.3 IL_00ae: ldc.i4.4 IL_00af: ldc.i4.5 IL_00b0: ldc.i4.6 IL_00b1: ldc.i4.7 IL_00b2: ldc.i4.8 IL_00b3: ldc.i4.s 9 IL_00b5: ldc.i4.s 10 IL_00b7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, int, int, int, int, int, int, int, int, int, int)"" IL_00bc: ret } "); } [Fact] public void Missing_CallSite() { string systemCoreSource = ExpressionTypeSource + DynamicAttributeSource + @" namespace System.Runtime.CompilerServices { public class CallSite<T> where T : class { public T Target; public static CallSite<T> Create(CallSiteBinder binder) { return null; } } public abstract class CallSiteBinder { } }"; var systemCoreRef = CreateCompilationWithMscorlib40(systemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d * d; } } "; CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.CallSite' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Runtime.CompilerServices.CallSite"), // error CS1969: One or more types required to compile a dynamic expression cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicRequiredTypesMissing)); } [Fact] public void Missing_CallSiteOfT() { string systemCoreSource = ExpressionTypeSource + DynamicAttributeSource + @" namespace System.Runtime.CompilerServices { public class CallSite { } public class CallSiteBinder {} }"; var systemCoreRef = CreateCompilationWithMscorlib40(systemCoreSource, assemblyName: GetUniqueName()).EmitToImageReference(); var csrtRef = MakeCSharpRuntime(systemCore: systemCoreRef); string source = @" class C { dynamic F(dynamic d) { return d * d; } } "; CreateCompilationWithMscorlib40(source, new[] { systemCoreRef, csrtRef }).VerifyEmitDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.CallSite`1' is not defined or imported // return d * d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Runtime.CompilerServices.CallSite`1").WithLocation(6, 16), // (6,16): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.CallSite`1.Create' // return d * d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("System.Runtime.CompilerServices.CallSite`1", "Create").WithLocation(6, 16) ); } #endregion #region Generated Metadata (call-site containers, delegates) /// <summary> /// Dev11 doesn't include name of explicit interface implementation method into site container name. /// </summary> [Fact] public void ExplicitInterfaceImplementation() { string source = @" public interface I { dynamic M(dynamic d); } public class C : I { dynamic I.M(dynamic d) { return checked(d * d); } }"; CompileAndVerifyIL(source, "C.I.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void CallSiteContainers() { string source = @" public class C { public void M1(dynamic d) { d.m(1,2,3); } public void M2(dynamic d) { d.m(1,2,3); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var containers = c.GetMembers().OfType<NamedTypeSymbol>().ToArray(); Assert.Equal(2, containers.Length); foreach (var container in containers) { Assert.Equal(Accessibility.Private, container.DeclaredAccessibility); Assert.True(container.IsStatic); Assert.Equal(SpecialType.System_Object, container.BaseType().SpecialType); AssertEx.SetEqual(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(container.GetAttributes())); var members = container.GetMembers(); Assert.Equal(1, members.Length); var field = (FieldSymbol)members[0]; Assert.Equal(Accessibility.Public, field.DeclaredAccessibility); Assert.True(field.IsStatic); Assert.False(field.IsReadOnly); Assert.Equal("System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int>>", field.TypeWithAnnotations.ToDisplayString()); Assert.Equal(0, field.GetAttributes().Length); switch (container.Name) { case "<>o__0": Assert.Equal("<>p__0", field.Name); break; case "<>o__1": Assert.Equal("<>p__0", field.Name); break; default: throw TestExceptionUtilities.UnexpectedValue(container.Name); } } }); } [Fact] public void CallSiteContainers_MultipleSitesInMethod_DisplayClass() { string source = @" public class C { public void M1(dynamic d) { d.m(1); d.m(1,2); var x = new System.Action(() => d.m()); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.Equal(2, c.GetMembers().OfType<NamedTypeSymbol>().Count()); var container = c.GetMember<NamedTypeSymbol>("<>o__0"); // all call-site storage fields of the method are added to a single container: var memberNames = container.GetMembers().Select(m => m.Name); AssertEx.SetEqual(new[] { "<>p__0", "<>p__1", "<>p__2" }, memberNames); var displayClass = c.GetMember<NamedTypeSymbol>("<>c__DisplayClass0_0"); var d = displayClass.GetMember<FieldSymbol>("d"); var attributes = d.GetAttributes(); Assert.Equal(1, attributes.Length); Assert.Equal("System.Runtime.CompilerServices.DynamicAttribute", attributes[0].AttributeClass.ToDisplayString()); }); } [Fact] public void Iterator() { string source = @" using System.Collections.Generic; public class C { public IEnumerable<dynamic> M1() { dynamic d = 1; yield return 1; d = d + 2; yield return d; } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var c = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var iteratorClass = c.GetMember<NamedTypeSymbol>("<M1>d__0"); foreach (var member in iteratorClass.GetMembers()) { switch (member.Kind) { case SymbolKind.Field: // no field is marked with DynamicAttribute Assert.Equal(0, member.GetAttributes().Length); break; case SymbolKind.Method: var attributes = ((MethodSymbol)member).GetReturnTypeAttributes(); switch (member.MetadataName) { case "System.Collections.Generic.IEnumerator<dynamic>.get_Current": case "System.Collections.Generic.IEnumerable<dynamic>.GetEnumerator": Assert.Equal(1, attributes.Length); break; default: Assert.Equal(0, attributes.Length); break; } break; case SymbolKind.Property: // "Current" properties or return types are not marked with attributes break; default: throw TestExceptionUtilities.UnexpectedValue(member.Kind); } } var container = c.GetMember<NamedTypeSymbol>("<>o__0"); Assert.Equal(1, container.GetMembers().Length); }); } [Fact] [WorkItem(625282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625282")] public void GenericIterator() { string source = @" using System.Collections.Generic; class C { dynamic d = null; public IEnumerable<T> Run<T>() { yield return d; } } "; CompileAndVerifyIL(source, "C.<Run>d__1<T>.System.Collections.IEnumerator.MoveNext", @" { // Code size 123 (0x7b) .maxstack 4 .locals init (int V_0, C V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Run>d__1<T>.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C C.<Run>d__1<T>.<>4__this"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: brfalse.s IL_0017 IL_0011: ldloc.0 IL_0012: ldc.i4.1 IL_0013: beq.s IL_0072 IL_0015: ldc.i4.0 IL_0016: ret IL_0017: ldarg.0 IL_0018: ldc.i4.m1 IL_0019: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_001e: ldarg.0 IL_001f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_0024: brtrue.s IL_004a IL_0026: ldc.i4.0 IL_0027: ldtoken ""T"" IL_002c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0031: ldtoken ""C"" IL_0036: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0040: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0045: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_004f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, T> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Target"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__1<T>.<>p__0"" IL_0059: ldloc.1 IL_005a: ldfld ""dynamic C.d"" IL_005f: callvirt ""T System.Func<System.Runtime.CompilerServices.CallSite, object, T>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0064: stfld ""T C.<Run>d__1<T>.<>2__current"" IL_0069: ldarg.0 IL_006a: ldc.i4.1 IL_006b: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_0070: ldc.i4.1 IL_0071: ret IL_0072: ldarg.0 IL_0073: ldc.i4.m1 IL_0074: stfld ""int C.<Run>d__1<T>.<>1__state"" IL_0079: ldc.i4.0 IL_007a: ret } "); } [Fact] public void NoDynamicAttributeOnCallSiteStorageField() { string source = @" using System.Collections.Generic; public class C { public dynamic M(dynamic d, List<dynamic> a, Dictionary<dynamic, dynamic[]>[] b) { return d(a, b); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var container = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("<>o__0"); Assert.Equal(0, container.GetMembers().Single().GetAttributes().Length); }); } [Fact] public void GeneratedDelegates() { string source = @" using System.Collections.Generic; public class C { public dynamic M(dynamic d) { return d(ref d); } }"; var verifier = CompileAndVerifyWithCSharp(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: peModule => { var d = peModule.GlobalNamespace.GetMember<NamedTypeSymbol>("<>F{00000010}"); // the type: Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(4, d.TypeParameters.Length); Assert.True(d.IsSealed); Assert.Equal(CharSet.Ansi, d.MarshallingCharSet); Assert.Equal(SpecialType.System_MulticastDelegate, d.BaseType().SpecialType); Assert.Equal(0, d.Interfaces().Length); AssertEx.SetEqual(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(d.GetAttributes())); // members: var members = d.GetMembers(); Assert.Equal(2, members.Length); foreach (var member in members) { Assert.Equal(Accessibility.Public, member.DeclaredAccessibility); switch (member.Name) { case ".ctor": Assert.False(member.IsStatic); Assert.False(member.IsSealed); Assert.False(member.IsVirtual); break; case "Invoke": Assert.False(member.IsStatic); Assert.False(member.IsSealed); Assert.True(member.IsVirtual); break; default: throw TestExceptionUtilities.UnexpectedValue(member.Name); } } }); } [Fact] public void GenericContainer1() { string source = @" public class C { public T M<T>(dynamic d) { return (T)d; } } "; CompileAndVerifyIL(source, "C.M<T>", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""T"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, T> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, T>> C.<>o__0<T>.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""T System.Func<System.Runtime.CompilerServices.CallSite, object, T>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret } "); } [Fact] public void GenericContainer2() { string source = @" public class E<P, Q, R> {} public class C<U> { public dynamic M<S,T>(dynamic d) { E<S, T, U> dict = null; return d(ref dict); } } "; CompileAndVerifyIL(source, "C<U>.M<S, T>", @" { // Code size 86 (0x56) .maxstack 7 .locals init (E<S, T, U> V_0) //dict IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""C<U>"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 9 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>> C<U>.<>o__0<S, T>.<>p__0"" IL_004d: ldarg.1 IL_004e: ldloca.s V_0 IL_0050: callvirt ""object <>F{00000010}<System.Runtime.CompilerServices.CallSite, object, E<S, T, U>, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref E<S, T, U>)"" IL_0055: ret } "); } [Fact] public void GenericContainer3() { string source = @" public class C<U> { public dynamic M(dynamic d) { return d(); } } "; CompileAndVerifyIL(source, "C<U>.M", @" { // Code size 71 (0x47) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0031 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C<U>"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.1 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C<U>.<>o__0.<>p__0"" IL_0040: ldarg.1 IL_0041: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: ret } "); } [Fact] public void GenericContainer4() { string source = @" using System; class C { public static int F<T>(dynamic d, Type t, T x) where T : struct { if (d.GetType() == t && ((T)d).Equals(x)) { return 1; } return 2; } } "; CompileAndVerifyWithCSharp(source); } [Fact] [WorkItem(627091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627091")] public void GenericContainer_Lambda() { string source = @" class C { static void Goo<T>(T a, dynamic b) { System.Action f = () => Goo(a, b); } } "; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0<T>.<Goo>b__0", @" { // Code size 123 (0x7b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0005: brtrue.s IL_0050 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.3 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.1 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.0 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0046: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_0055: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>>.Target"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>> C.<>o__0<T>.<>p__0"" IL_005f: ldtoken ""C"" IL_0064: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0069: ldarg.0 IL_006a: ldfld ""T C.<>c__DisplayClass0_0<T>.a"" IL_006f: ldarg.0 IL_0070: ldfld ""dynamic C.<>c__DisplayClass0_0<T>.b"" IL_0075: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, T, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, T, object)"" IL_007a: ret } "); } [Fact] public void DynamicErasure_MetadataConstant() { string source = @" public class C { const dynamic f = null; public void M(dynamic arg = null) { const dynamic local = null; } } "; CompileAndVerifyWithMscorlib40(source, new[] { SystemCoreRef }); } [Fact, WorkItem(16, "http://roslyn.codeplex.com/workitem/16")] public void RemoveAtOfKeywordAsDynamicMemberName() { string source = @" using System; class C { // field public int @default = 123; // prop protected string @if { get; set; } int @else { get { return 1; } } // event public event Action @event { add { } remove { } } // Method internal int @while(dynamic @void) { return 456; } static void Main() { dynamic dyn = new C(); if (dyn.@default == 123) { dynamic @static = 12; dyn.@default = dyn.@while(@static); } dyn.@if = [email protected](); dyn.@event += (Action)( () => { dyn.@if = [email protected](); }); } } "; CompileAndVerifyIL(source, "C.Main", @" { // Code size 1130 (0x46a) .maxstack 13 .locals init (C.<>c__DisplayClass11_0 V_0, //CS$<>8__locals0 object V_1, //static object V_2, bool V_3, object V_4, System.Action V_5) IL_0000: newobj ""C.<>c__DisplayClass11_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: newobj ""C..ctor()"" IL_000c: stfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_0011: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0016: brtrue.s IL_0044 IL_0018: ldc.i4.0 IL_0019: ldc.i4.s 83 IL_001b: ldtoken ""C"" IL_0020: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0025: ldc.i4.1 IL_0026: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0049: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__2"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0058: brtrue.s IL_0090 IL_005a: ldc.i4.0 IL_005b: ldc.i4.s 13 IL_005d: ldtoken ""C"" IL_0062: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0067: ldc.i4.2 IL_0068: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006d: dup IL_006e: ldc.i4.0 IL_006f: ldc.i4.0 IL_0070: ldnull IL_0071: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0076: stelem.ref IL_0077: dup IL_0078: ldc.i4.1 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0086: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0090: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_0095: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__11.<>p__1"" IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00a4: brtrue.s IL_00d5 IL_00a6: ldc.i4.0 IL_00a7: ldstr ""default"" IL_00ac: ldtoken ""C"" IL_00b1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b6: ldc.i4.1 IL_00b7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bc: dup IL_00bd: ldc.i4.0 IL_00be: ldc.i4.0 IL_00bf: ldnull IL_00c0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c5: stelem.ref IL_00c6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00da: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00df: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__0"" IL_00e4: ldloc.0 IL_00e5: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_00ea: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ef: ldc.i4.s 123 IL_00f1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00f6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00fb: brfalse IL_01bf IL_0100: ldc.i4.s 12 IL_0102: box ""int"" IL_0107: stloc.1 IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_010d: brtrue.s IL_0148 IL_010f: ldc.i4.0 IL_0110: ldstr ""default"" IL_0115: ldtoken ""C"" IL_011a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_011f: ldc.i4.2 IL_0120: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0125: dup IL_0126: ldc.i4.0 IL_0127: ldc.i4.0 IL_0128: ldnull IL_0129: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012e: stelem.ref IL_012f: dup IL_0130: ldc.i4.1 IL_0131: ldc.i4.0 IL_0132: ldnull IL_0133: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0138: stelem.ref IL_0139: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_013e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0143: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_0148: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_014d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0152: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__4"" IL_0157: ldloc.0 IL_0158: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_015d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_0162: brtrue.s IL_019e IL_0164: ldc.i4.0 IL_0165: ldstr ""while"" IL_016a: ldnull IL_016b: ldtoken ""C"" IL_0170: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0175: ldc.i4.2 IL_0176: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_017b: dup IL_017c: ldc.i4.0 IL_017d: ldc.i4.0 IL_017e: ldnull IL_017f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0184: stelem.ref IL_0185: dup IL_0186: ldc.i4.1 IL_0187: ldc.i4.0 IL_0188: ldnull IL_0189: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_018e: stelem.ref IL_018f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0194: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0199: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_019e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_01a3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_01a8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__3"" IL_01ad: ldloc.0 IL_01ae: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_01b3: ldloc.1 IL_01b4: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01b9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01be: pop IL_01bf: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_01c4: brtrue.s IL_01ff IL_01c6: ldc.i4.0 IL_01c7: ldstr ""if"" IL_01cc: ldtoken ""C"" IL_01d1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01d6: ldc.i4.2 IL_01d7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01dc: dup IL_01dd: ldc.i4.0 IL_01de: ldc.i4.0 IL_01df: ldnull IL_01e0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01e5: stelem.ref IL_01e6: dup IL_01e7: ldc.i4.1 IL_01e8: ldc.i4.0 IL_01e9: ldnull IL_01ea: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01ef: stelem.ref IL_01f0: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01f5: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01fa: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_01ff: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_0204: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0209: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__7"" IL_020e: ldloc.0 IL_020f: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_0214: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_0219: brtrue.s IL_024b IL_021b: ldc.i4.0 IL_021c: ldstr ""ToString"" IL_0221: ldnull IL_0222: ldtoken ""C"" IL_0227: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_022c: ldc.i4.1 IL_022d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0232: dup IL_0233: ldc.i4.0 IL_0234: ldc.i4.0 IL_0235: ldnull IL_0236: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_023b: stelem.ref IL_023c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0241: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0246: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_024b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_0250: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0255: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__6"" IL_025a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_025f: brtrue.s IL_0290 IL_0261: ldc.i4.0 IL_0262: ldstr ""else"" IL_0267: ldtoken ""C"" IL_026c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0271: ldc.i4.1 IL_0272: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0277: dup IL_0278: ldc.i4.0 IL_0279: ldc.i4.0 IL_027a: ldnull IL_027b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0280: stelem.ref IL_0281: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0286: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_028b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_0290: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_0295: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_029a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__5"" IL_029f: ldloc.0 IL_02a0: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_02a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02aa: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02af: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_02b4: pop IL_02b5: ldloc.0 IL_02b6: ldfld ""dynamic C.<>c__DisplayClass11_0.dyn"" IL_02bb: stloc.2 IL_02bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02c1: brtrue.s IL_02e2 IL_02c3: ldc.i4.0 IL_02c4: ldstr ""event"" IL_02c9: ldtoken ""C"" IL_02ce: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02d3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_02d8: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_02dd: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02e7: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_02ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__11.<>p__12"" IL_02f1: ldloc.2 IL_02f2: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_02f7: stloc.3 IL_02f8: ldloc.3 IL_02f9: brtrue.s IL_0348 IL_02fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0300: brtrue.s IL_0331 IL_0302: ldc.i4.0 IL_0303: ldstr ""event"" IL_0308: ldtoken ""C"" IL_030d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0312: ldc.i4.1 IL_0313: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0318: dup IL_0319: ldc.i4.0 IL_031a: ldc.i4.0 IL_031b: ldnull IL_031c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0321: stelem.ref IL_0322: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0327: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_032c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0331: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0336: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_033b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__11.<>p__11"" IL_0340: ldloc.2 IL_0341: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0346: stloc.s V_4 IL_0348: ldloc.0 IL_0349: ldftn ""void C.<>c__DisplayClass11_0.<Main>b__0()"" IL_034f: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0354: stloc.s V_5 IL_0356: ldloc.3 IL_0357: brtrue IL_040c IL_035c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_0361: brtrue.s IL_03a0 IL_0363: ldc.i4 0x80 IL_0368: ldstr ""event"" IL_036d: ldtoken ""C"" IL_0372: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0377: ldc.i4.2 IL_0378: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_037d: dup IL_037e: ldc.i4.0 IL_037f: ldc.i4.0 IL_0380: ldnull IL_0381: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0386: stelem.ref IL_0387: dup IL_0388: ldc.i4.1 IL_0389: ldc.i4.0 IL_038a: ldnull IL_038b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0390: stelem.ref IL_0391: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0396: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_039b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03a5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_03aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__11.<>p__15"" IL_03af: ldloc.2 IL_03b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03b5: brtrue.s IL_03ed IL_03b7: ldc.i4.0 IL_03b8: ldc.i4.s 63 IL_03ba: ldtoken ""C"" IL_03bf: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_03c4: ldc.i4.2 IL_03c5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_03ca: dup IL_03cb: ldc.i4.0 IL_03cc: ldc.i4.0 IL_03cd: ldnull IL_03ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_03d3: stelem.ref IL_03d4: dup IL_03d5: ldc.i4.1 IL_03d6: ldc.i4.1 IL_03d7: ldnull IL_03d8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_03dd: stelem.ref IL_03de: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_03e3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_03e8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03f2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Target"" IL_03f7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__14"" IL_03fc: ldloc.s V_4 IL_03fe: ldloc.s V_5 IL_0400: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, System.Action)"" IL_0405: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_040a: pop IL_040b: ret IL_040c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0411: brtrue.s IL_0451 IL_0413: ldc.i4 0x104 IL_0418: ldstr ""add_event"" IL_041d: ldnull IL_041e: ldtoken ""C"" IL_0423: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0428: ldc.i4.2 IL_0429: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_042e: dup IL_042f: ldc.i4.0 IL_0430: ldc.i4.0 IL_0431: ldnull IL_0432: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0437: stelem.ref IL_0438: dup IL_0439: ldc.i4.1 IL_043a: ldc.i4.1 IL_043b: ldnull IL_043c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0441: stelem.ref IL_0442: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0447: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_044c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0451: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0456: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>>.Target"" IL_045b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>> C.<>o__11.<>p__13"" IL_0460: ldloc.2 IL_0461: ldloc.s V_5 IL_0463: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, System.Action)"" IL_0468: pop IL_0469: ret } "); } #endregion #region Conversions [Fact] public void LocalFunctionArgumentConversion() { string src = @" using System; public class C { static void Main() { int capture1 = 0; void L1(int x) => Console.Write(x); Action<int> L2(int x) { Console.Write(capture1); Console.Write(x); void L3(int y) { Console.Write(y + x); } return L3; } dynamic d = 2; L1(d); dynamic l3 = L2(d); l3(d); } }"; CompileAndVerifyWithCSharp(src, expectedOutput: "2024", parseOptions: _localFunctionParseOptions).VerifyDiagnostics(); CompileAndVerifyIL(src, "C.Main", parseOptions: _localFunctionParseOptions, expectedOptimizedIL: @" { // Code size 242 (0xf2) .maxstack 7 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 object V_1, //d object V_2) //l3 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: stfld ""int C.<>c__DisplayClass0_0.capture1"" IL_0008: ldc.i4.2 IL_0009: box ""int"" IL_000e: stloc.1 IL_000f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0014: brtrue.s IL_003a IL_0016: ldc.i4.0 IL_0017: ldtoken ""int"" IL_001c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0021: ldtoken ""C"" IL_0026: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0030: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0035: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0049: ldloc.1 IL_004a: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004f: call ""void C.<Main>g__L1|0_0(int)"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0059: brtrue.s IL_007f IL_005b: ldc.i4.0 IL_005c: ldtoken ""int"" IL_0061: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0066: ldtoken ""C"" IL_006b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_008e: ldloc.1 IL_008f: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: ldloca.s V_0 IL_0096: call ""System.Action<int> C.<Main>g__L2|0_1(int, ref C.<>c__DisplayClass0_0)"" IL_009b: stloc.2 IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00a1: brtrue.s IL_00db IL_00a3: ldc.i4 0x100 IL_00a8: ldtoken ""C"" IL_00ad: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b2: ldc.i4.2 IL_00b3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b8: dup IL_00b9: ldc.i4.0 IL_00ba: ldc.i4.0 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: dup IL_00c3: ldc.i4.1 IL_00c4: ldc.i4.0 IL_00c5: ldnull IL_00c6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cb: stelem.ref IL_00cc: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00e0: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__2"" IL_00ea: ldloc.2 IL_00eb: ldloc.1 IL_00ec: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f1: ret }"); } [Fact] public void Conversion_Assignment() { string source = @" public class C { dynamic d = null; void M() { int i = d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_003a: ldarg.0 IL_003b: ldfld ""dynamic C.d"" IL_0040: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0045: pop IL_0046: ret } "); } [Fact] public void Conversion_Implicit() { string source = @" public class C { public int M(dynamic d) { return d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret } "); } [Fact] public void Conversion_Explicit() { string source = @" public class C { public int M(dynamic d) { return (int)d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""int"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret }"); } [Fact] public void Conversion_Implicit_Checked() { string source = @" public class C { public int M(dynamic d) { checked { return d; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.1 IL_0008: ldtoken ""int"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret }"); } [Fact] public void Conversion_Explicit_Checked() { string source = @" public class C { public int M(dynamic d) { checked { return (int)d; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 17 IL_0009: ldtoken ""int"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret }"); } [Fact] public void Conversion_Implicit_Reference_Return() { string source = @" class D { } class C { public D M(dynamic d) { return d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 65 (0x41) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""D"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: ret } "); } [Fact] public void Conversion_Implicit_Reference_Assignment() { string source = @" class D { } class C { D x; public void M(dynamic d) { x = d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 71 (0x47) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""D"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__1.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: stfld ""D C.x"" IL_0046: ret } "); } [Fact] public void Conversion_Explicit_Reference() { string source = @" class D { } class C { public D M(dynamic d) { return (D)d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 66 (0x42) .maxstack 3 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002c IL_0007: ldc.i4.s 16 IL_0009: ldtoken ""D"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, D>> C.<>o__0.<>p__0"" IL_003b: ldarg.1 IL_003c: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0041: ret } "); } [Fact] public void Conversion_ArrayIndex() { string source = @" public class C { public object M(object[] a, dynamic d) { return a[d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 32 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret } "); } [Fact] public void Conversion_ArrayIndex_Checked() { string source = @" public class C { public object M(object[] a, dynamic d) { return checked(a[d]); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 33 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret }"); } [Fact] public void Conversion_ArrayIndex_Explicit() { string source = @" public class C { public object M(object[] a, dynamic d) { return a[(int)d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 68 (0x44) .maxstack 4 IL_0000: ldarg.1 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__0"" IL_003c: ldarg.2 IL_003d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: ldelem.ref IL_0043: ret }"); } [Fact] public void IdentityConversion1() { string source = @" public class C { public object M(dynamic d) { return d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.1 IL_0001: ret } "); } [Fact] public void IdentityConversion2() { string source = @" public class C { public static void M() { dynamic d = new object(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: newobj ""object..ctor()"" IL_0005: pop IL_0006: ret } "); } [Fact] public void IdentityConversion3() { string source = @" public class C { public dynamic Null() { return null; } }"; CompileAndVerifyIL(source, "C.Null", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret } "); } [Fact] public void Boxing_ReturnValue() { string source = @" public class C { public dynamic Int32() { return 1; } }"; CompileAndVerifyIL(source, "C.Int32", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ret } "); } [Fact] public void Boxing_AssignmentToDynamicField1() { string source = @" class C { dynamic d; void M() { d = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: box ""bool"" IL_0007: stfld ""dynamic C.d"" IL_000c: ret } "); } [Fact] public void Boxing_AssignmentToDynamicField2() { string source = @" class C { dynamic d; void M() { new C { d = true }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.1 IL_0006: box ""bool"" IL_000b: stfld ""dynamic C.d"" IL_0010: ret } "); } [Fact] public void Boxing_AssignmentToDynamicIndex() { string source = @" class C { dynamic this[int i] { get { return 1; } set { } } void M() { this[1] = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: box ""bool"" IL_0008: call ""void C.this[int].set"" IL_000d: ret } "); } [Fact] public void Boxing_AssignmentToProperty1() { string source = @" class C { dynamic d { get; set; } void M() { this.d = true; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: box ""bool"" IL_0007: call ""void C.d.set"" IL_000c: ret } "); } [Fact] public void Boxing_AssignmentToProperty2() { string source = @" class C { dynamic d { get; set; } void M() { new C { d = true }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.1 IL_0006: box ""bool"" IL_000b: callvirt ""void C.d.set"" IL_0010: ret } "); } [Fact] public void IsAs() { string source = @" using System.Collections.Generic; public class C { public bool IsObject(dynamic d) { return d is List<object>; } public bool IsDynamic(dynamic d) { return d is List<dynamic>; } public List<dynamic> As(dynamic d) { return d as List<dynamic>; } }"; // TODO: Why does RefEmit use fat header with maxstack = 2? var verifier = CompileAndVerifyWithCSharp(source, symbolValidator: module => { var pe = (PEModuleSymbol)module; // all occurrences of List<dynamic> and List<object> should be unified to a single TypeSpec: Assert.Equal(1, pe.Module.GetMetadataReader().GetTableRowCount(TableIndex.TypeSpec)); }); verifier.VerifyIL("C.IsObject", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret } ", realIL: true); verifier.VerifyIL("C.IsDynamic", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ldnull IL_0007: cgt.un IL_0009: ret } ", realIL: true); verifier.VerifyIL("C.As", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: isinst ""System.Collections.Generic.List<object>"" IL_0006: ret } ", realIL: true); } [Fact] public void DelegateCreation() { string source = @" using System; public class C { dynamic d = null; Action a; public virtual void M() { a = new System.Action(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""System.Action"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__2.<>p__0"" IL_003b: ldarg.0 IL_003c: ldfld ""dynamic C.d"" IL_0041: callvirt ""System.Action System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: ldftn ""void System.Action.Invoke()"" IL_004c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0051: stfld ""System.Action C.a"" IL_0056: ret } "); } [Fact] public void TestThrowDynamic() { var source = @" using System; class C { public static void Main() { M(null); M(new Exception()); M(new ArgumentException()); M(string.Empty); } static void M(dynamic d) { try { throw d; } catch (Exception ex) { System.Console.WriteLine(ex.GetType().Name); } } } "; CompileAndVerifyWithCSharp(source, expectedOutput: @"NullReferenceException Exception ArgumentException RuntimeBinderException"); } #endregion #region Operators [Fact] public void Multiplication_Dynamic_Dynamic() { string source = @" public class C { public dynamic M(dynamic d) { return d * d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Multiplication_Dynamic_Static() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c * d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.1 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_0053: ret } "); } [Fact] public void Multiplication_Dynamic_Literal() { string source = @" public class C { public dynamic M(dynamic d) { return d * 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.3 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldc.i4.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0053: ret } "); } [Fact] public void Multiplication_Checked() { string source = @" public class C { public dynamic M(dynamic d) { return checked(d * d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 26 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Division() { string source = @" public class C { public dynamic M(dynamic d) { return d / d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 12 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Remainder() { string source = @" public class C { public dynamic M(dynamic d) { return d % d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 25 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void LeftShift() { string source = @" public class C { public dynamic M(dynamic d) { return d << d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 19 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void RightShift() { string source = @" public class C { public dynamic M(dynamic d) { return d >> d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 41 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void And() { string source = @" public class C { public dynamic M(dynamic d) { return d & d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 83 (0x53) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldc.i4.2 IL_0009: ldtoken ""C"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldc.i4.2 IL_0014: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0019: dup IL_001a: ldc.i4.0 IL_001b: ldc.i4.0 IL_001c: ldnull IL_001d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0022: stelem.ref IL_0023: dup IL_0024: ldc.i4.1 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0041: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004b: ldarg.1 IL_004c: ldarg.1 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0052: ret } "); } [Fact] public void Or() { string source = @" public class C { public dynamic M(dynamic d) { return d | d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 36 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Xor() { string source = @" public class C { public dynamic M(dynamic d) { return d ^ d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 14 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret } "); } [Fact] public void Equal() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 == d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 13 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void NotEqual() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 != d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 35 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void LessThan() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 < d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 20 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void GreaterThan() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 > d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 15 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void LessThanEquals() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 <= d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 21 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void GreaterThanEquals() { string source = @" public class C { public dynamic M(dynamic d1, dynamic d2) { return d1 >= d2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: ret }"); } [Fact] public void UnaryPlus() { string source = @" public class C { public dynamic M(dynamic d) { return +d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 29 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret } "); } [Fact] public void UnaryMinus() { string source = @" public class C { public dynamic M(dynamic d) { return -d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 28 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret }"); } [Fact] public void BitwiseComplement() { string source = @" public class C { public dynamic M(dynamic d) { return ~d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 73 (0x49) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 82 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: ret } "); } [Fact] public void BooleanOperation_IsTrue() { string source = @" class C { public static int M() { dynamic dy = null; if (dy.Property_bool) { return 1; } else { return 0; } } }"; var verifier = CompileAndVerifyIL(source, "C.M", expectedUnoptimizedIL: @" { // Code size 169 (0xa9) .maxstack 10 .locals init (object V_0, //dy bool V_1, int V_2) -IL_0000: nop -IL_0001: ldnull IL_0002: stloc.0 -IL_0003: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0038 IL_000c: ldc.i4.0 IL_000d: ldc.i4.s 83 IL_000f: ldtoken ""C"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldc.i4.1 IL_001a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001f: dup IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0033: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004c: brfalse.s IL_0050 IL_004e: br.s IL_007f IL_0050: ldc.i4.0 IL_0051: ldstr ""Property_bool"" IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.1 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008e: ldloc.0 IL_008f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0099: stloc.1 ~IL_009a: ldloc.1 IL_009b: brfalse.s IL_00a2 -IL_009d: nop -IL_009e: ldc.i4.1 IL_009f: stloc.2 IL_00a0: br.s IL_00a7 -IL_00a2: nop -IL_00a3: ldc.i4.0 IL_00a4: stloc.2 IL_00a5: br.s IL_00a7 -IL_00a7: ldloc.2 IL_00a8: ret } ", expectedOptimizedIL: @" { // Code size 154 (0x9a) .maxstack 10 .locals init (object V_0) //dy IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_007a IL_004b: ldc.i4.0 IL_004c: ldstr ""Property_bool"" IL_0051: ldtoken ""C"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldc.i4.1 IL_005c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0061: dup IL_0062: ldc.i4.0 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0089: ldloc.0 IL_008a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008f: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: brfalse.s IL_0098 IL_0096: ldc.i4.1 IL_0097: ret IL_0098: ldc.i4.0 IL_0099: ret } "); } [Fact] public void BooleanOperation_Not() { string source = @" public class C { public static int M(dynamic d) { if (!d) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 149 (0x95) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0047: brtrue.s IL_0075 IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 34 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.1 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0070: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0075: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0084: ldarg.0 IL_0085: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008a: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008f: brfalse.s IL_0093 IL_0091: ldc.i4.1 IL_0092: ret IL_0093: ldc.i4.0 IL_0094: ret } "); } [Fact] public void BooleanOperation_And() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if (d1 && d2) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 236 (0xec) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0047: brtrue.s IL_0075 IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 84 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.1 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0070: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0075: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_007a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0084: ldarg.0 IL_0085: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008a: brtrue.s IL_00e0 IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0091: brtrue.s IL_00c8 IL_0093: ldc.i4.8 IL_0094: ldc.i4.2 IL_0095: ldtoken ""C"" IL_009a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009f: ldc.i4.2 IL_00a0: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a5: dup IL_00a6: ldc.i4.0 IL_00a7: ldc.i4.0 IL_00a8: ldnull IL_00a9: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ae: stelem.ref IL_00af: dup IL_00b0: ldc.i4.1 IL_00b1: ldc.i4.0 IL_00b2: ldnull IL_00b3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b8: stelem.ref IL_00b9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00be: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00cd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d7: ldarg.0 IL_00d8: ldarg.1 IL_00d9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00de: br.s IL_00e1 IL_00e0: ldarg.0 IL_00e1: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e6: brfalse.s IL_00ea IL_00e8: ldc.i4.1 IL_00e9: ret IL_00ea: ldc.i4.0 IL_00eb: ret }"); } [WorkItem(547676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547676")] [Fact] public void BooleanOperation_Bug547676() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if ((d1 == 1) && d2 && d2) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 480 (0x1e0) .maxstack 10 .locals init (object V_0, object V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__5"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0047: brtrue.s IL_007f IL_0049: ldc.i4.0 IL_004a: ldc.i4.s 13 IL_004c: ldtoken ""C"" IL_0051: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0056: ldc.i4.2 IL_0057: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.i4.0 IL_005f: ldnull IL_0060: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0065: stelem.ref IL_0066: dup IL_0067: ldc.i4.1 IL_0068: ldc.i4.3 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_008e: ldarg.0 IL_008f: ldc.i4.1 IL_0090: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0095: stloc.1 IL_0096: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_009b: brtrue.s IL_00c9 IL_009d: ldc.i4.0 IL_009e: ldc.i4.s 84 IL_00a0: ldtoken ""C"" IL_00a5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00aa: ldc.i4.1 IL_00ab: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b0: dup IL_00b1: ldc.i4.0 IL_00b2: ldc.i4.0 IL_00b3: ldnull IL_00b4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b9: stelem.ref IL_00ba: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bf: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00c9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00ce: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_00d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_00d8: ldloc.1 IL_00d9: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00de: brtrue.s IL_0134 IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00e5: brtrue.s IL_011c IL_00e7: ldc.i4.8 IL_00e8: ldc.i4.2 IL_00e9: ldtoken ""C"" IL_00ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00f3: ldc.i4.2 IL_00f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00f9: dup IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.0 IL_00fc: ldnull IL_00fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0102: stelem.ref IL_0103: dup IL_0104: ldc.i4.1 IL_0105: ldc.i4.0 IL_0106: ldnull IL_0107: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010c: stelem.ref IL_010d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0112: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0117: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_011c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0121: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0126: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_012b: ldloc.1 IL_012c: ldarg.1 IL_012d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0132: br.s IL_0135 IL_0134: ldloc.1 IL_0135: stloc.0 IL_0136: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_013b: brtrue.s IL_0169 IL_013d: ldc.i4.0 IL_013e: ldc.i4.s 84 IL_0140: ldtoken ""C"" IL_0145: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_014a: ldc.i4.1 IL_014b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0150: dup IL_0151: ldc.i4.0 IL_0152: ldc.i4.0 IL_0153: ldnull IL_0154: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0159: stelem.ref IL_015a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_015f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0164: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_0169: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_016e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0173: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__4"" IL_0178: ldloc.0 IL_0179: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_017e: brtrue.s IL_01d4 IL_0180: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_0185: brtrue.s IL_01bc IL_0187: ldc.i4.8 IL_0188: ldc.i4.2 IL_0189: ldtoken ""C"" IL_018e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0193: ldc.i4.2 IL_0194: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0199: dup IL_019a: ldc.i4.0 IL_019b: ldc.i4.0 IL_019c: ldnull IL_019d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01a2: stelem.ref IL_01a3: dup IL_01a4: ldc.i4.1 IL_01a5: ldc.i4.0 IL_01a6: ldnull IL_01a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01ac: stelem.ref IL_01ad: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01b2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01b7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01c1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_01c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__3"" IL_01cb: ldloc.0 IL_01cc: ldarg.1 IL_01cd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01d2: br.s IL_01d5 IL_01d4: ldloc.0 IL_01d5: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01da: brfalse.s IL_01de IL_01dc: ldc.i4.1 IL_01dd: ret IL_01de: ldc.i4.0 IL_01df: ret }"); } [Fact] public void BooleanOperation_Or_Dynamic_Dynamic() { string source = @" public class C { public static int M(dynamic d1, dynamic d2) { if (d1 || d2) { return 1; } else { return 0; } } }"; // Dev11 emits less efficient code: // IsTrue(IsTrue(d1) ? d1 : Or(d1, d2)) // // Roslyn optimizes away the second dynamic call IsTrue on d1: // IsTrue(d1) || IsTrue(Or(d1, d2)) CompileAndVerifyIL(source, "C.M", @" { // Code size 237 (0xed) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldarg.0 IL_0043: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: brtrue IL_00e9 IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0052: brtrue.s IL_0080 IL_0054: ldc.i4.0 IL_0055: ldc.i4.s 83 IL_0057: ldtoken ""C"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldc.i4.1 IL_0062: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0067: dup IL_0068: ldc.i4.0 IL_0069: ldc.i4.0 IL_006a: ldnull IL_006b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0070: stelem.ref IL_0071: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0076: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0080: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0085: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0094: brtrue.s IL_00cc IL_0096: ldc.i4.8 IL_0097: ldc.i4.s 36 IL_0099: ldtoken ""C"" IL_009e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a3: ldc.i4.2 IL_00a4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a9: dup IL_00aa: ldc.i4.0 IL_00ab: ldc.i4.0 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.1 IL_00b5: ldc.i4.0 IL_00b6: ldnull IL_00b7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bc: stelem.ref IL_00bd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00cc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00db: ldarg.0 IL_00dc: ldarg.1 IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00e2: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e7: brfalse.s IL_00eb IL_00e9: ldc.i4.1 IL_00ea: ret IL_00eb: ldc.i4.0 IL_00ec: ret } "); } [Fact] public void BooleanOperation_Or_Static_Dynamic() { string source = @" public class C { public static int M(bool b, dynamic d) { if (b || d) { return 1; } else { return 0; } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 166 (0xa6) .maxstack 10 IL_0000: ldarg.0 IL_0001: brtrue IL_00a2 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_000b: brtrue.s IL_0039 IL_000d: ldc.i4.0 IL_000e: ldc.i4.s 83 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.1 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.0 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0034: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_004d: brtrue.s IL_0085 IL_004f: ldc.i4.8 IL_0050: ldc.i4.s 36 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.2 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.1 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.0 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0080: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_008a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0094: ldarg.0 IL_0095: ldarg.1 IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_009b: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a0: brfalse.s IL_00a4 IL_00a2: ldc.i4.1 IL_00a3: ret IL_00a4: ldc.i4.0 IL_00a5: ret }"); } [Fact] public void BooleanOperation_Or_ConstantOperand_False() { string source = @" class C { int M() { dynamic d = null; return (false || d) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 162 (0xa2) .maxstack 10 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_0081 IL_004b: ldc.i4.8 IL_004c: ldc.i4.s 36 IL_004e: ldtoken ""C"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldc.i4.2 IL_0059: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005e: dup IL_005f: ldc.i4.0 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0090: ldc.i4.0 IL_0091: ldloc.0 IL_0092: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0097: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009c: brtrue.s IL_00a0 IL_009e: ldc.i4.2 IL_009f: ret IL_00a0: ldc.i4.1 IL_00a1: ret } "); } [Fact] public void BooleanOperation_Or_ConstantOperand_True() { string source = @" class C { int M() { dynamic d = null; return (true || d) ? 1 : 2; } } "; // Dev11 emits: // IsTrue(IsTrue(true) ? true : Or(true, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [Fact] public void BooleanOperation_Add_ConstantOperand_False() { string source = @" class C { int M() { dynamic d = null; return (false && d) ? 1 : 2; } } "; // Dev11: IsTrue(IsFalse(false) ? false : And(false, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } "); } [Fact] public void BooleanOperation_ConstantPropagation() { string source = @" class C { int M() { dynamic d = null; return (!(false && d) || d) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret } "); } [Fact] public void BooleanOperation_ConstantPropagation2() { string source = @" class C { int M() { dynamic d = null; return ((dynamic)false) ? 1 : 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: ret } "); } [Fact] public void BooleanOperation_Add_ConstantOperand_True() { string source = @" class C { int M() { dynamic d = null; return (true && d) ? 1 : 2; } } "; // Dev11: IsTrue(IsFalse(true) ? true : And(true, d)) ? 1 : 2 // Roslyn: IsTrue(And(true, d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 161 (0xa1) .maxstack 10 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 83 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__1"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0049: brtrue.s IL_0080 IL_004b: ldc.i4.8 IL_004c: ldc.i4.2 IL_004d: ldtoken ""C"" IL_0052: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0057: ldc.i4.2 IL_0058: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005d: dup IL_005e: ldc.i4.0 IL_005f: ldc.i4.3 IL_0060: ldnull IL_0061: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0066: stelem.ref IL_0067: dup IL_0068: ldc.i4.1 IL_0069: ldc.i4.0 IL_006a: ldnull IL_006b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0070: stelem.ref IL_0071: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0076: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0080: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_0085: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__0.<>p__0"" IL_008f: ldc.i4.1 IL_0090: ldloc.0 IL_0091: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0096: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009b: brtrue.s IL_009f IL_009d: ldc.i4.2 IL_009e: ret IL_009f: ldc.i4.1 IL_00a0: ret } "); } [Fact] public void BooleanOperation_Or_BoxedOperand() { string source = @" class C { bool b = false; dynamic M() { dynamic d = null; return b || d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 8 .locals init (object V_0, //d bool V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldfld ""bool C.b"" IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: brtrue.s IL_0060 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0049 IL_0013: ldc.i4.8 IL_0014: ldc.i4.s 36 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0058: ldloc.1 IL_0059: ldloc.0 IL_005a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_005f: ret IL_0060: ldloc.1 IL_0061: box ""bool"" IL_0066: ret } "); } [Fact] public void BooleanOperation_And_BoxedOperand() { string source = @" class C { bool b = false; dynamic M() { dynamic d = null; return b && d; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 8 .locals init (object V_0, //d bool V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldfld ""bool C.b"" IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: brfalse.s IL_005f IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0048 IL_0013: ldc.i4.8 IL_0014: ldc.i4.2 IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__0"" IL_0057: ldloc.1 IL_0058: ldloc.0 IL_0059: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_005e: ret IL_005f: ldloc.1 IL_0060: box ""bool"" IL_0065: ret } "); } [Fact] public void BooleanOperation_Or_UserDefinedTrue_Dynamic() { string source = @" class B { public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b || d) { return 1; } return 2; } } "; // Dev11: IsTrue(B.op_True(b) ? b : Or(b, d)) ? 1 : 2 // Roslyn: B.op_True(b) || IsTrue(Or(b,d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 10 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool B.op_True(B)"" IL_000d: brtrue IL_00ae IL_0012: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0017: brtrue.s IL_0045 IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 83 IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.1 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0059: brtrue.s IL_0091 IL_005b: ldc.i4.8 IL_005c: ldc.i4.s 36 IL_005e: ldtoken ""C"" IL_0063: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0068: ldc.i4.2 IL_0069: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006e: dup IL_006f: ldc.i4.0 IL_0070: ldc.i4.1 IL_0071: ldnull IL_0072: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0077: stelem.ref IL_0078: dup IL_0079: ldc.i4.1 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_00a0: ldloc.0 IL_00a1: ldarg.1 IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ac: brfalse.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret } "); } /// <summary> /// Implicit conversion has precedence over operator true/false. /// </summary> [Fact] public void BooleanOperation_Or_UserDefinedImplicitConversion_Dynamic() { string source = @" class B { public static implicit operator bool(B t) { return true; } public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b || d) { return 1; } return 2; } } "; // Dev11: IsTrue(B.op_Implicit(b) ? b : Or(b, d)) ? 1 : 2 // Roslyn: B.op_Implicit(b) || IsTrue(Or(b,d)) ? 1 : 2 CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 10 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool B.op_Implicit(B)"" IL_000d: brtrue IL_00ae IL_0012: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0017: brtrue.s IL_0045 IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 83 IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.1 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0059: brtrue.s IL_0091 IL_005b: ldc.i4.8 IL_005c: ldc.i4.s 36 IL_005e: ldtoken ""C"" IL_0063: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0068: ldc.i4.2 IL_0069: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006e: dup IL_006f: ldc.i4.0 IL_0070: ldc.i4.1 IL_0071: ldnull IL_0072: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0077: stelem.ref IL_0078: dup IL_0079: ldc.i4.1 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_00a0: ldloc.0 IL_00a1: ldarg.1 IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ac: brfalse.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret }"); } [Fact] public void BooleanOperation_And_UserDefinedTrue_Dynamic() { string source = @" class B { public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b && d) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 177 (0xb1) .maxstack 10 .locals init (B V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0042: ldarg.0 IL_0043: ldfld ""B C.b"" IL_0048: stloc.0 IL_0049: ldloc.0 IL_004a: call ""bool B.op_False(B)"" IL_004f: brtrue.s IL_00a5 IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0056: brtrue.s IL_008d IL_0058: ldc.i4.8 IL_0059: ldc.i4.2 IL_005a: ldtoken ""C"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: ldc.i4.2 IL_0065: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006a: dup IL_006b: ldc.i4.0 IL_006c: ldc.i4.1 IL_006d: ldnull IL_006e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0073: stelem.ref IL_0074: dup IL_0075: ldc.i4.1 IL_0076: ldc.i4.0 IL_0077: ldnull IL_0078: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007d: stelem.ref IL_007e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0083: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0088: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_008d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0092: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0097: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_009c: ldloc.0 IL_009d: ldarg.1 IL_009e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a3: br.s IL_00a6 IL_00a5: ldloc.0 IL_00a6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ab: brfalse.s IL_00af IL_00ad: ldc.i4.1 IL_00ae: ret IL_00af: ldc.i4.2 IL_00b0: ret } "); } /// <summary> /// Implicit conversion has precedence over operator true/false. /// </summary> [Fact] public void BooleanOperation_And_UserDefinedImplicitConversion_Dynamic() { string source = @" class B { public static implicit operator bool(B t) { return true; } public static bool operator true(B t) { return true; } public static bool operator false(B t) { return false; } } class C { B b = new B(); int M(dynamic d) { if (b && d) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 177 (0xb1) .maxstack 10 .locals init (B V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 83 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0042: ldarg.0 IL_0043: ldfld ""B C.b"" IL_0048: stloc.0 IL_0049: ldloc.0 IL_004a: call ""bool B.op_Implicit(B)"" IL_004f: brfalse.s IL_00a5 IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0056: brtrue.s IL_008d IL_0058: ldc.i4.8 IL_0059: ldc.i4.2 IL_005a: ldtoken ""C"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: ldc.i4.2 IL_0065: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006a: dup IL_006b: ldc.i4.0 IL_006c: ldc.i4.1 IL_006d: ldnull IL_006e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0073: stelem.ref IL_0074: dup IL_0075: ldc.i4.1 IL_0076: ldc.i4.0 IL_0077: ldnull IL_0078: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007d: stelem.ref IL_007e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0083: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0088: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_008d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_0092: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0097: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__1.<>p__0"" IL_009c: ldloc.0 IL_009d: ldarg.1 IL_009e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_00a3: br.s IL_00a6 IL_00a5: ldloc.0 IL_00a6: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ab: brfalse.s IL_00af IL_00ad: ldc.i4.1 IL_00ae: ret IL_00af: ldc.i4.2 IL_00b0: ret } "); } private const string StructWithUserDefinedBooleanOperators = @" struct S { private int num; private string str; public S(int num, char chr) { this.num = num; this.str = chr.ToString(); } public S(int num, string str) { this.num = num; this.str = str; } public static S operator & (S x, S y) { return new S(x.num & y.num, '(' + x.str + '&' + y.str + ')'); } public static S operator | (S x, S y) { return new S(x.num | y.num, '(' + x.str + '|' + y.str + ')'); } public static bool operator true(S s) { return s.num != 0; } public static bool operator false(S s) { return s.num == 0; } public override string ToString() { return this.num.ToString() + ':' + this.str; } } "; [Fact] public void BooleanOperation_NestedOperators1() { // Analogue to OperatorTests.TestUserDefinedLogicalOperators1. string source = @" using System; class C { static void Main() { dynamic f = new S(0, 'f'); dynamic t = new S(1, 't'); Console.WriteLine((f && f) && f); Console.WriteLine((f && f) && t); Console.WriteLine((f && t) && f); Console.WriteLine((f && t) && t); Console.WriteLine((t && f) && f); Console.WriteLine((t && f) && t); Console.WriteLine((t && t) && f); Console.WriteLine((t && t) && t); Console.WriteLine('-'); Console.WriteLine((f && f) || f); Console.WriteLine((f && f) || t); Console.WriteLine((f && t) || f); Console.WriteLine((f && t) || t); Console.WriteLine((t && f) || f); Console.WriteLine((t && f) || t); Console.WriteLine((t && t) || f); Console.WriteLine((t && t) || t); Console.WriteLine('-'); Console.WriteLine((f || f) && f); Console.WriteLine((f || f) && t); Console.WriteLine((f || t) && f); Console.WriteLine((f || t) && t); Console.WriteLine((t || f) && f); Console.WriteLine((t || f) && t); Console.WriteLine((t || t) && f); Console.WriteLine((t || t) && t); Console.WriteLine('-'); Console.WriteLine((f || f) || f); Console.WriteLine((f || f) || t); Console.WriteLine((f || t) || f); Console.WriteLine((f || t) || t); Console.WriteLine((t || f) || f); Console.WriteLine((t || f) || t); Console.WriteLine((t || t) || f); Console.WriteLine((t || t) || t); Console.WriteLine('-'); Console.WriteLine(f && (f && f)); Console.WriteLine(f && (f && t)); Console.WriteLine(f && (t && f)); Console.WriteLine(f && (t && t)); Console.WriteLine(t && (f && f)); Console.WriteLine(t && (f && t)); Console.WriteLine(t && (t && f)); Console.WriteLine(t && (t && t)); Console.WriteLine('-'); Console.WriteLine(f && (f || f)); Console.WriteLine(f && (f || t)); Console.WriteLine(f && (t || f)); Console.WriteLine(f && (t || t)); Console.WriteLine(t && (f || f)); Console.WriteLine(t && (f || t)); Console.WriteLine(t && (t || f)); Console.WriteLine(t && (t || t)); Console.WriteLine('-'); Console.WriteLine(f || (f && f)); Console.WriteLine(f || (f && t)); Console.WriteLine(f || (t && f)); Console.WriteLine(f || (t && t)); Console.WriteLine(t || (f && f)); Console.WriteLine(t || (f && t)); Console.WriteLine(t || (t && f)); Console.WriteLine(t || (t && t)); Console.WriteLine('-'); Console.WriteLine(f || (f || f)); Console.WriteLine(f || (f || t)); Console.WriteLine(f || (t || f)); Console.WriteLine(f || (t || t)); Console.WriteLine(t || (f || f)); Console.WriteLine(t || (f || t)); Console.WriteLine(t || (t || f)); Console.WriteLine(t || (t || t)); } } " + StructWithUserDefinedBooleanOperators; string output = @"0:f 0:f 0:f 0:f 0:(t&f) 0:(t&f) 0:((t&t)&f) 1:((t&t)&t) - 0:(f|f) 1:(f|t) 0:(f|f) 1:(f|t) 0:((t&f)|f) 1:((t&f)|t) 1:(t&t) 1:(t&t) - 0:(f|f) 0:(f|f) 0:((f|t)&f) 1:((f|t)&t) 0:(t&f) 1:(t&t) 0:(t&f) 1:(t&t) - 0:((f|f)|f) 1:((f|f)|t) 1:(f|t) 1:(f|t) 1:t 1:t 1:t 1:t - 0:f 0:f 0:f 0:f 0:(t&f) 0:(t&f) 0:(t&(t&f)) 1:(t&(t&t)) - 0:f 0:f 0:f 0:f 0:(t&(f|f)) 1:(t&(f|t)) 1:(t&t) 1:(t&t) - 0:(f|f) 0:(f|f) 0:(f|(t&f)) 1:(f|(t&t)) 1:t 1:t 1:t 1:t - 0:(f|(f|f)) 1:(f|(f|t)) 1:(f|t) 1:(f|t) 1:t 1:t 1:t 1:t"; CompileAndVerifyWithCSharp(source: source, expectedOutput: output); } [Fact] public void BooleanOperation_NestedOperators2() { // Analogue to OperatorTests.TestUserDefinedLogicalOperators2. string source = @" using System; class C { static void Main() { dynamic f = new S(0, 'f'); dynamic t = new S(1, 't'); Console.Write((f && f) && f ? 1 : 0); Console.Write((f && f) && t ? 1 : 0); Console.Write((f && t) && f ? 1 : 0); Console.Write((f && t) && t ? 1 : 0); Console.Write((t && f) && f ? 1 : 0); Console.Write((t && f) && t ? 1 : 0); Console.Write((t && t) && f ? 1 : 0); Console.Write((t && t) && t ? 1 : 0); Console.WriteLine('-'); Console.Write((f && f) || f ? 1 : 0); Console.Write((f && f) || t ? 1 : 0); Console.Write((f && t) || f ? 1 : 0); Console.Write((f && t) || t ? 1 : 0); Console.Write((t && f) || f ? 1 : 0); Console.Write((t && f) || t ? 1 : 0); Console.Write((t && t) || f ? 1 : 0); Console.Write((t && t) || t ? 1 : 0); Console.WriteLine('-'); Console.Write((f || f) && f ? 1 : 0); Console.Write((f || f) && t ? 1 : 0); Console.Write((f || t) && f ? 1 : 0); Console.Write((f || t) && t ? 1 : 0); Console.Write((t || f) && f ? 1 : 0); Console.Write((t || f) && t ? 1 : 0); Console.Write((t || t) && f ? 1 : 0); Console.Write((t || t) && t ? 1 : 0); Console.WriteLine('-'); Console.Write((f || f) || f ? 1 : 0); Console.Write((f || f) || t ? 1 : 0); Console.Write((f || t) || f ? 1 : 0); Console.Write((f || t) || t ? 1 : 0); Console.Write((t || f) || f ? 1 : 0); Console.Write((t || f) || t ? 1 : 0); Console.Write((t || t) || f ? 1 : 0); Console.Write((t || t) || t ? 1 : 0); Console.WriteLine('-'); Console.Write(f && (f && f) ? 1 : 0); Console.Write(f && (f && t) ? 1 : 0); Console.Write(f && (t && f) ? 1 : 0); Console.Write(f && (t && t) ? 1 : 0); Console.Write(t && (f && f) ? 1 : 0); Console.Write(t && (f && t) ? 1 : 0); Console.Write(t && (t && f) ? 1 : 0); Console.Write(t && (t && t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f && (f || f) ? 1 : 0); Console.Write(f && (f || t) ? 1 : 0); Console.Write(f && (t || f) ? 1 : 0); Console.Write(f && (t || t) ? 1 : 0); Console.Write(t && (f || f) ? 1 : 0); Console.Write(t && (f || t) ? 1 : 0); Console.Write(t && (t || f) ? 1 : 0); Console.Write(t && (t || t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f || (f && f) ? 1 : 0); Console.Write(f || (f && t) ? 1 : 0); Console.Write(f || (t && f) ? 1 : 0); Console.Write(f || (t && t) ? 1 : 0); Console.Write(t || (f && f) ? 1 : 0); Console.Write(t || (f && t) ? 1 : 0); Console.Write(t || (t && f) ? 1 : 0); Console.Write(t || (t && t) ? 1 : 0); Console.WriteLine('-'); Console.Write(f || (f || f) ? 1 : 0); Console.Write(f || (f || t) ? 1 : 0); Console.Write(f || (t || f) ? 1 : 0); Console.Write(f || (t || t) ? 1 : 0); Console.Write(t || (f || f) ? 1 : 0); Console.Write(t || (f || t) ? 1 : 0); Console.Write(t || (t || f) ? 1 : 0); Console.Write(t || (t || t) ? 1 : 0); } } " + StructWithUserDefinedBooleanOperators; string output = @" 00000001- 01010111- 00010101- 01111111- 00000001- 00000111- 00011111- 01111111"; CompileAndVerifyWithCSharp(source: source, expectedOutput: output); } [Fact] public void BooleanOperation_EvaluationOrder() { string source = @" public class C { public static dynamic f(ref dynamic d) { d = false; return d; } public static void Main() { dynamic d = true; if (d || f(ref d)) { return; } else { throw null; } } } "; CompileAndVerifyWithCSharp(source, expectedOutput: ""); } [Fact] public void Multiplication_CompoundAssignment() { string source = @" public class C { public dynamic M(dynamic d) { return d *= d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Multiplication_CompoundAssignment_Checked() { string source = @" public class C { public dynamic M(dynamic d) { return checked(d *= d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.1 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Multiplication_CompoundAssignment_DiscardResult() { string source = @" public class C { public void M(dynamic d) { d *= d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 86 (0x56) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 69 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.1 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: starg.s V_1 IL_0055: ret } "); } [Fact] public void Addition_CompoundAssignment() { string source = @" public class C { public dynamic M(dynamic d, dynamic v) { return d += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003d IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 63 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldarg.1 IL_004d: ldarg.2 IL_004e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0053: dup IL_0054: starg.s V_1 IL_0056: ret } "); } [Fact] public void Addition_EventHandler_SimpleConversion() { string source = @" public class C { event System.Action e; dynamic v; public void M() { e += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_0006: brtrue.s IL_002c IL_0008: ldc.i4.0 IL_0009: ldtoken ""System.Action"" IL_000e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0022: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0027: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_002c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_0031: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>>.Target"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>> C.<>o__4.<>p__0"" IL_003b: ldarg.0 IL_003c: ldfld ""dynamic C.v"" IL_0041: callvirt ""System.Action System.Func<System.Runtime.CompilerServices.CallSite, object, System.Action>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0046: call ""void C.e.add"" IL_004b: ret }"); } [Fact] public void PostIncrement() { string source = @" public class C { public dynamic M(dynamic d) { return d++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 8 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 54 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0044: ldloc.0 IL_0045: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004a: starg.s V_1 IL_004c: ldloc.0 IL_004d: ret }"); } [Fact] public void PostDecrement() { string source = @" public class C { public dynamic M(dynamic d) { return d--; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 8 .locals init (object V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0035 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 49 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.1 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0030: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0044: ldloc.0 IL_0045: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004a: starg.s V_1 IL_004c: ldloc.0 IL_004d: ret }"); } [Fact] public void PreIncrement() { string source = @" public class C { public dynamic M(dynamic d) { return ++d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 54 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: dup IL_0049: starg.s V_1 IL_004b: ret }"); } [Fact] public void PreDecrement() { string source = @" public class C { public dynamic M(dynamic d) { return --d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0033 IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 49 IL_000a: ldtoken ""C"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.1 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0029: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0033: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0038: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0042: ldarg.1 IL_0043: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0048: dup IL_0049: starg.s V_1 IL_004b: ret } "); } [Fact] public void PostIncrement_DynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static void M() { d[0]++; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 10 .locals init (object V_0) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: ldelem.ref IL_0008: stloc.0 IL_0009: ldc.i4.0 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_000f: brtrue.s IL_003d IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 54 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004c: ldloc.0 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0052: stelem.ref IL_0053: ret }"); } [Fact] public void PreIncrement_DynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static void M() { ++d[0]; } } "; // TODO (tomat): IL_0050 ... IL_0053 and V_1 could be optimized away CompileAndVerifyIL(source, "C.M", @" { // Code size 86 (0x56) .maxstack 8 .locals init (object[] V_0, object V_1) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_000b: brtrue.s IL_0039 IL_000d: ldc.i4.0 IL_000e: ldc.i4.s 54 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.1 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.0 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0034: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_003e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0048: ldloc.0 IL_0049: ldc.i4.0 IL_004a: ldelem.ref IL_004b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldc.i4.0 IL_0053: ldloc.1 IL_0054: stelem.ref IL_0055: ret }"); } [Fact] public void PreIncrement_DynamicMemberAccess() { string source = @" class C { dynamic d = null; dynamic M() { return ++d.P; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 243 (0xf3) .maxstack 10 .locals init (object V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_003a IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 54 IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.1 IL_001c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0021: dup IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002a: stelem.ref IL_002b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0030: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0035: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004e: brtrue.s IL_007f IL_0050: ldc.i4.0 IL_0051: ldstr ""P"" IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.1 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0075: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_007f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0084: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_008e: ldloc.0 IL_008f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0094: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0099: stloc.1 IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_009f: brtrue.s IL_00da IL_00a1: ldc.i4.0 IL_00a2: ldstr ""P"" IL_00a7: ldtoken ""C"" IL_00ac: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b1: ldc.i4.2 IL_00b2: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b7: dup IL_00b8: ldc.i4.0 IL_00b9: ldc.i4.0 IL_00ba: ldnull IL_00bb: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c0: stelem.ref IL_00c1: dup IL_00c2: ldc.i4.1 IL_00c3: ldc.i4.0 IL_00c4: ldnull IL_00c5: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ca: stelem.ref IL_00cb: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d0: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d5: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00df: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00e4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00e9: ldloc.0 IL_00ea: ldloc.1 IL_00eb: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f0: pop IL_00f1: ldloc.1 IL_00f2: ret } "); } [Fact] public void PostIncrement_DynamicMemberAccess() { string source = @" class C { dynamic d = null; dynamic M() { return d.P++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 243 (0xf3) .maxstack 11 .locals init (object V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_003d IL_000e: ldc.i4.0 IL_000f: ldstr ""P"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__1"" IL_004c: ldloc.0 IL_004d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0052: stloc.1 IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0058: brtrue.s IL_0093 IL_005a: ldc.i4.0 IL_005b: ldstr ""P"" IL_0060: ldtoken ""C"" IL_0065: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006a: ldc.i4.2 IL_006b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0070: dup IL_0071: ldc.i4.0 IL_0072: ldc.i4.0 IL_0073: ldnull IL_0074: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0079: stelem.ref IL_007a: dup IL_007b: ldc.i4.1 IL_007c: ldc.i4.0 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0089: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0093: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0098: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_00a2: ldloc.0 IL_00a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00a8: brtrue.s IL_00d6 IL_00aa: ldc.i4.0 IL_00ab: ldc.i4.s 54 IL_00ad: ldtoken ""C"" IL_00b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b7: ldc.i4.1 IL_00b8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bd: dup IL_00be: ldc.i4.0 IL_00bf: ldc.i4.0 IL_00c0: ldnull IL_00c1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c6: stelem.ref IL_00c7: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cc: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d1: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00db: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_00e5: ldloc.1 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00eb: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00f0: pop IL_00f1: ldloc.1 IL_00f2: ret } "); } [Fact] public void PreIncrement_DynamicIndexerAccess() { string source = @" class C { dynamic d = null; int F() { return 0; } dynamic M() { return ++d[F()]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 262 (0x106) .maxstack 9 .locals init (object V_0, int V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: call ""int C.F()"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0013: brtrue.s IL_0041 IL_0015: ldc.i4.0 IL_0016: ldc.i4.s 54 IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.1 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0037: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0046: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__1"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_0055: brtrue.s IL_008b IL_0057: ldc.i4.0 IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.2 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.1 IL_0074: ldc.i4.1 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__0"" IL_009a: ldloc.0 IL_009b: ldloc.1 IL_009c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a6: stloc.2 IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00ac: brtrue.s IL_00ec IL_00ae: ldc.i4.0 IL_00af: ldtoken ""C"" IL_00b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b9: ldc.i4.3 IL_00ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bf: dup IL_00c0: ldc.i4.0 IL_00c1: ldc.i4.0 IL_00c2: ldnull IL_00c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c8: stelem.ref IL_00c9: dup IL_00ca: ldc.i4.1 IL_00cb: ldc.i4.1 IL_00cc: ldnull IL_00cd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d2: stelem.ref IL_00d3: dup IL_00d4: ldc.i4.2 IL_00d5: ldc.i4.0 IL_00d6: ldnull IL_00d7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00dc: stelem.ref IL_00dd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00e2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00f1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_00f6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00fb: ldloc.0 IL_00fc: ldloc.1 IL_00fd: ldloc.2 IL_00fe: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_0103: pop IL_0104: ldloc.2 IL_0105: ret }"); } [Fact] public void PostIncrement_DynamicIndexerAccess() { string source = @" class C { dynamic d = null; int F() { return 0; } dynamic M() { return d[F()]++; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 262 (0x106) .maxstack 12 .locals init (object V_0, int V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: call ""int C.F()"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0013: brtrue.s IL_0049 IL_0015: ldc.i4.0 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.1 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__1"" IL_0058: ldloc.0 IL_0059: ldloc.1 IL_005a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_005f: stloc.2 IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_0065: brtrue.s IL_00a5 IL_0067: ldc.i4.0 IL_0068: ldtoken ""C"" IL_006d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0072: ldc.i4.3 IL_0073: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0078: dup IL_0079: ldc.i4.0 IL_007a: ldc.i4.0 IL_007b: ldnull IL_007c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0081: stelem.ref IL_0082: dup IL_0083: ldc.i4.1 IL_0084: ldc.i4.1 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.2 IL_008e: ldc.i4.0 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00aa: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_00af: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__2.<>p__2"" IL_00b4: ldloc.0 IL_00b5: ldloc.1 IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00bb: brtrue.s IL_00e9 IL_00bd: ldc.i4.0 IL_00be: ldc.i4.s 54 IL_00c0: ldtoken ""C"" IL_00c5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ca: ldc.i4.1 IL_00cb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d0: dup IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldnull IL_00d4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d9: stelem.ref IL_00da: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00df: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00e9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ee: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00f8: ldloc.2 IL_00f9: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00fe: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_0103: pop IL_0104: ldloc.2 IL_0105: ret }"); } [Fact] public void NullCoalescing() { string source = @" class C { dynamic d = null; object o = null; void M() { var x = d ?? o; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: brtrue.s IL_000f IL_0008: ldarg.0 IL_0009: ldfld ""object C.o"" IL_000e: pop IL_000f: ret } "); } #endregion #region Invoke, InvokeMember, InvokeConstructor [Fact] public void InvokeMember_Dynamic() { string source = @" public class C { public dynamic M(dynamic d) { return d.m(null, this, d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.1 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.1 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c.F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.1 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.2 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static_SimpleName() { string source = @" public class C { public dynamic M(C c, dynamic d) { return F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0055 IL_0007: ldc.i4.2 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.2 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.2 IL_0034: ldc.i4.1 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: dup IL_003d: ldc.i4.3 IL_003e: ldc.i4.0 IL_003f: ldnull IL_0040: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0045: stelem.ref IL_0046: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0050: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_005a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0064: ldarg.0 IL_0065: ldnull IL_0066: ldarg.0 IL_0067: ldarg.2 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_006d: ret } "); } [Fact] public void InvokeMember_Static_ResultDiscarded() { string source = @" public class C { public void M(C c, dynamic d) { F(null, this, d); } public int F(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 114 (0x72) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0059 IL_0007: ldc.i4 0x102 IL_000c: ldstr ""F"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.4 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.2 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.1 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.0 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004f: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0054: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_005e: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>>.Target"" IL_0063: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>> C.<>o__0.<>p__0"" IL_0068: ldarg.0 IL_0069: ldnull IL_006a: ldarg.0 IL_006b: ldarg.2 IL_006c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, C, object, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_0071: ret } "); } [Fact] [WorkItem(622532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622532")] public void InvokeMember_Static_Outer() { string source = @" using System; public class A { public static void M(int x) { } public class B { public void F() { dynamic d = null; M(d); } } }"; // Dev11 passes "this" to the site, which is wrong. CompileAndVerifyIL(source, "A.B.F", @" { // Code size 104 (0x68) .maxstack 9 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0048 IL_0009: ldc.i4 0x100 IL_000e: ldstr ""M"" IL_0013: ldnull IL_0014: ldtoken ""A.B"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.s 33 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_004d: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0057: ldtoken ""A"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldloc.0 IL_0062: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: ret } "); } [Fact] [WorkItem(622532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622532")] public void InvokeMember_Static_Outer_AmbiguousAtRuntime() { string source = @" using System; public class A { public static void M(A x) { } public void M(string x) { } public class B { public void F() { dynamic d = null; M(d); } } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { new A.B().F(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; // Dev11 passes "this" to the site, which is wrong. CompileAndVerifyIL(source, "A.B.F", @" { // Code size 104 (0x68) .maxstack 9 .locals init (object V_0) //d IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0007: brtrue.s IL_0048 IL_0009: ldc.i4 0x100 IL_000e: ldstr ""M"" IL_0013: ldnull IL_0014: ldtoken ""A.B"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.s 33 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_004d: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> A.B.<>o__0.<>p__0"" IL_0057: ldtoken ""A"" IL_005c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0061: ldloc.0 IL_0062: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: ret }"); CompileAndVerifyWithCSharp(source, expectedOutput: "The call is ambiguous between the following methods or properties: 'A.M(A)' and 'A.M(string)'"); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_StaticProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static Color Color { get; set; } public static void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 286 (0x11e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: call ""Color C.Color.get"" IL_0059: ldarg.0 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0064: brtrue.s IL_00a4 IL_0066: ldc.i4 0x100 IL_006b: ldstr ""M2"" IL_0070: ldnull IL_0071: ldtoken ""C"" IL_0076: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007b: ldc.i4.2 IL_007c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0081: dup IL_0082: ldc.i4.0 IL_0083: ldc.i4.1 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.1 IL_008d: ldc.i4.0 IL_008e: ldnull IL_008f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0094: stelem.ref IL_0095: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a9: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b3: call ""Color C.Color.get"" IL_00b8: ldarg.0 IL_00b9: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c3: brtrue.s IL_0103 IL_00c5: ldc.i4 0x100 IL_00ca: ldstr ""M3"" IL_00cf: ldnull IL_00d0: ldtoken ""C"" IL_00d5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00da: ldc.i4.2 IL_00db: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e0: dup IL_00e1: ldc.i4.0 IL_00e2: ldc.i4.1 IL_00e3: ldnull IL_00e4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e9: stelem.ref IL_00ea: dup IL_00eb: ldc.i4.1 IL_00ec: ldc.i4.0 IL_00ed: ldnull IL_00ee: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f3: stelem.ref IL_00f4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f9: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fe: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0103: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0108: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0112: call ""Color C.Color.get"" IL_0117: ldarg.0 IL_0118: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_011d: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_InstanceProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public Color Color { get; set; } public static void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); // Dev11 crashes on this one } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 304 (0x130) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__0"" IL_0055: ldtoken ""Color"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_006a: brtrue.s IL_00ab IL_006c: ldc.i4 0x100 IL_0071: ldstr ""M2"" IL_0076: ldnull IL_0077: ldtoken ""C"" IL_007c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0081: ldc.i4.2 IL_0082: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0087: dup IL_0088: ldc.i4.0 IL_0089: ldc.i4.s 33 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.1 IL_0094: ldc.i4.0 IL_0095: ldnull IL_0096: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009b: stelem.ref IL_009c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00b0: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_00b5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__1"" IL_00ba: ldtoken ""Color"" IL_00bf: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c4: ldarg.0 IL_00c5: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_00ca: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_00cf: brtrue.s IL_0110 IL_00d1: ldc.i4 0x100 IL_00d6: ldstr ""M3"" IL_00db: ldnull IL_00dc: ldtoken ""C"" IL_00e1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00e6: ldc.i4.2 IL_00e7: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00ec: dup IL_00ed: ldc.i4.0 IL_00ee: ldc.i4.s 33 IL_00f0: ldnull IL_00f1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f6: stelem.ref IL_00f7: dup IL_00f8: ldc.i4.1 IL_00f9: ldc.i4.0 IL_00fa: ldnull IL_00fb: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0100: stelem.ref IL_0101: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0106: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_010b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_0110: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_0115: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_011a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__4.<>p__2"" IL_011f: ldtoken ""Color"" IL_0124: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0129: ldarg.0 IL_012a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_012f: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_StaticContext_Parameter() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static void F(Color Color, dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); // Dev11 crashes on this one } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 274 (0x112) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.0 IL_0055: ldarg.1 IL_0056: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_0060: brtrue.s IL_00a0 IL_0062: ldc.i4 0x100 IL_0067: ldstr ""M2"" IL_006c: ldnull IL_006d: ldtoken ""C"" IL_0072: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0077: ldc.i4.2 IL_0078: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_007d: dup IL_007e: ldc.i4.0 IL_007f: ldc.i4.1 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.1 IL_0089: ldc.i4.0 IL_008a: ldnull IL_008b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0090: stelem.ref IL_0091: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0096: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a5: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00af: ldarg.0 IL_00b0: ldarg.1 IL_00b1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00bb: brtrue.s IL_00fb IL_00bd: ldc.i4 0x100 IL_00c2: ldstr ""M3"" IL_00c7: ldnull IL_00c8: ldtoken ""C"" IL_00cd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00d2: ldc.i4.2 IL_00d3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d8: dup IL_00d9: ldc.i4.0 IL_00da: ldc.i4.1 IL_00db: ldnull IL_00dc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e1: stelem.ref IL_00e2: dup IL_00e3: ldc.i4.1 IL_00e4: ldc.i4.0 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_0100: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_010a: ldarg.0 IL_010b: ldarg.1 IL_010c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0111: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_StaticProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public static Color Color { get; set; } public void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 286 (0x11e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: call ""Color C.Color.get"" IL_0059: ldarg.1 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0064: brtrue.s IL_00a4 IL_0066: ldc.i4 0x100 IL_006b: ldstr ""M2"" IL_0070: ldnull IL_0071: ldtoken ""C"" IL_0076: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007b: ldc.i4.2 IL_007c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0081: dup IL_0082: ldc.i4.0 IL_0083: ldc.i4.1 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.1 IL_008d: ldc.i4.0 IL_008e: ldnull IL_008f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0094: stelem.ref IL_0095: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a9: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b3: call ""Color C.Color.get"" IL_00b8: ldarg.1 IL_00b9: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c3: brtrue.s IL_0103 IL_00c5: ldc.i4 0x100 IL_00ca: ldstr ""M3"" IL_00cf: ldnull IL_00d0: ldtoken ""C"" IL_00d5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00da: ldc.i4.2 IL_00db: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e0: dup IL_00e1: ldc.i4.0 IL_00e2: ldc.i4.1 IL_00e3: ldnull IL_00e4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e9: stelem.ref IL_00ea: dup IL_00eb: ldc.i4.1 IL_00ec: ldc.i4.0 IL_00ed: ldnull IL_00ee: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f3: stelem.ref IL_00f4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f9: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fe: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0103: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0108: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0112: call ""Color C.Color.get"" IL_0117: ldarg.1 IL_0118: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_011d: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_Parameter() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public void F(Color Color, dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 274 (0x112) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.1 IL_0055: ldarg.2 IL_0056: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_0060: brtrue.s IL_00a0 IL_0062: ldc.i4 0x100 IL_0067: ldstr ""M2"" IL_006c: ldnull IL_006d: ldtoken ""C"" IL_0072: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0077: ldc.i4.2 IL_0078: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_007d: dup IL_007e: ldc.i4.0 IL_007f: ldc.i4.1 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.1 IL_0089: ldc.i4.0 IL_008a: ldnull IL_008b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0090: stelem.ref IL_0091: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0096: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00a5: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00aa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__1"" IL_00af: ldarg.1 IL_00b0: ldarg.2 IL_00b1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00b6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00bb: brtrue.s IL_00fb IL_00bd: ldc.i4 0x100 IL_00c2: ldstr ""M3"" IL_00c7: ldnull IL_00c8: ldtoken ""C"" IL_00cd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00d2: ldc.i4.2 IL_00d3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d8: dup IL_00d9: ldc.i4.0 IL_00da: ldc.i4.1 IL_00db: ldnull IL_00dc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e1: stelem.ref IL_00e2: dup IL_00e3: ldc.i4.1 IL_00e4: ldc.i4.0 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f1: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f6: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_0100: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__0.<>p__2"" IL_010a: ldarg.1 IL_010b: ldarg.2 IL_010c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0111: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InstanceContext_InstanceProperty() { string source = @" public class Color { public static void M1(string s) { } public static void M1(int s) { } public static void M2(string s) { } public void M2(int s) { } public void M2(int s, int q) { } public void M3(int s) { } public static void M3(int s, int q) { } } public class C { public Color Color { get; set; } public void F(dynamic d) { Color.M1(d); Color.M2(d); Color.M3(d); } } "; CompileAndVerifyIL(source, "C.F", @" { // Code size 289 (0x121) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""M1"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__0"" IL_0054: ldarg.0 IL_0055: call ""Color C.Color.get"" IL_005a: ldarg.1 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_0065: brtrue.s IL_00a5 IL_0067: ldc.i4 0x100 IL_006c: ldstr ""M2"" IL_0071: ldnull IL_0072: ldtoken ""C"" IL_0077: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007c: ldc.i4.2 IL_007d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0082: dup IL_0083: ldc.i4.0 IL_0084: ldc.i4.1 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.1 IL_008e: ldc.i4.0 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00a5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00aa: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_00af: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__1"" IL_00b4: ldarg.0 IL_00b5: call ""Color C.Color.get"" IL_00ba: ldarg.1 IL_00bb: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_00c0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_00c5: brtrue.s IL_0105 IL_00c7: ldc.i4 0x100 IL_00cc: ldstr ""M3"" IL_00d1: ldnull IL_00d2: ldtoken ""C"" IL_00d7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00dc: ldc.i4.2 IL_00dd: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e2: dup IL_00e3: ldc.i4.0 IL_00e4: ldc.i4.1 IL_00e5: ldnull IL_00e6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00eb: stelem.ref IL_00ec: dup IL_00ed: ldc.i4.1 IL_00ee: ldc.i4.0 IL_00ef: ldnull IL_00f0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f5: stelem.ref IL_00f6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00fb: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0100: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_010a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, Color, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>>.Target"" IL_010f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, Color, object>> C.<>o__4.<>p__2"" IL_0114: ldarg.0 IL_0115: call ""Color C.Color.get"" IL_011a: ldarg.1 IL_011b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, Color, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0120: ret }"); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InFieldInitializer() { string source = @" public class Color { public int F(int a) { return 1; } } public class C { Color Color; dynamic x = Color.F((dynamic)1); } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 115 (0x73) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0006: brtrue.s IL_0043 IL_0008: ldc.i4.0 IL_0009: ldstr ""F"" IL_000e: ldnull IL_000f: ldtoken ""C"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldc.i4.2 IL_001a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001f: dup IL_0020: ldc.i4.0 IL_0021: ldc.i4.s 33 IL_0023: ldnull IL_0024: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0029: stelem.ref IL_002a: dup IL_002b: ldc.i4.1 IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0039: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003e: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0048: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Target"" IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__2.<>p__0"" IL_0052: ldtoken ""Color"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.1 IL_005d: box ""int"" IL_0062: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0067: stfld ""dynamic C.x"" IL_006c: ldarg.0 IL_006d: call ""object..ctor()"" IL_0072: ret } "); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InScriptVariableInitializer() { var sourceLib = @" public class Color { public int F(int a) { return 1; } } "; var lib = CreateCompilation(sourceLib); string sourceScript = @" Color Color; dynamic x = Color.F((dynamic)1); "; var script = CreateCompilationWithMscorlib45( new[] { Parse(sourceScript, options: TestOptions.Script) }, new[] { new CSharpCompilationReference(lib), SystemCoreRef, CSharpRef }); var verifier = CompileAndVerify(script); verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"{ // Code size 158 (0x9e) .maxstack 10 .locals init (Script V_0, object V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""Script Script.<<Initialize>>d__0.<>4__this"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_000d: brtrue.s IL_0049 IL_000f: ldc.i4.0 IL_0010: ldstr ""F"" IL_0015: ldnull IL_0016: ldtoken ""Script"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__0.<>p__0"" IL_0058: ldloc.0 IL_0059: ldfld ""Color Script.Color"" IL_005e: ldc.i4.1 IL_005f: box ""int"" IL_0064: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0069: stfld ""dynamic Script.x"" IL_006e: ldnull IL_006f: stloc.1 IL_0070: leave.s IL_0089 } catch System.Exception { IL_0072: stloc.2 IL_0073: ldarg.0 IL_0074: ldc.i4.s -2 IL_0076: stfld ""int Script.<<Initialize>>d__0.<>1__state"" IL_007b: ldarg.0 IL_007c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> Script.<<Initialize>>d__0.<>t__builder"" IL_0081: ldloc.2 IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0087: leave.s IL_009d } IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Script.<<Initialize>>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> Script.<<Initialize>>d__0.<>t__builder"" IL_0097: ldloc.1 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_009d: ret }", realIL: true); } [Fact, WorkItem(649805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649805")] public void InvokeMember_ColorColor_InScriptMethod() { var sourceLib = @" public class Color { public int F(int a) { return 1; } } "; var lib = CreateCompilation(sourceLib); string sourceScript = @" Color Color; void Goo() { dynamic x = Color.F((dynamic)1); } "; var script = CreateCompilationWithMscorlib45( new[] { Parse(sourceScript, options: TestOptions.Script) }, new[] { new CSharpCompilationReference(lib), SystemCoreRef, CSharpRef }, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(script).VerifyIL("Goo", @" { // Code size 99 (0x63) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0005: brtrue.s IL_0041 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldnull IL_000e: ldtoken ""Script"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.1 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0037: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0046: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>>.Target"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>> Script.<>o__2.<>p__0"" IL_0050: ldarg.0 IL_0051: ldfld ""Color Script.Color"" IL_0056: ldc.i4.1 IL_0057: box ""int"" IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, Color, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, Color, object)"" IL_0061: pop IL_0062: ret } ", realIL: true); } [Fact] public void InvokeMember_UseCompileTimeType() { string source = @" class C { static char? nChar = null; static char Char = '\0'; static C c = new C(); static object obj = null; static dynamic d = new C(); static void M() { d.f(nChar); d.f(Char); d.f(c); d.f(obj); d.f(d); d.f(null); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 591 (0x24f) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.1 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, char?> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char?>> C.<>o__5.<>p__0"" IL_0054: ldsfld ""dynamic C.d"" IL_0059: ldsfld ""char? C.nChar"" IL_005e: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, char?>.Invoke(System.Runtime.CompilerServices.CallSite, object, char?)"" IL_0063: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_0068: brtrue.s IL_00a8 IL_006a: ldc.i4 0x100 IL_006f: ldstr ""f"" IL_0074: ldnull IL_0075: ldtoken ""C"" IL_007a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007f: ldc.i4.2 IL_0080: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0085: dup IL_0086: ldc.i4.0 IL_0087: ldc.i4.0 IL_0088: ldnull IL_0089: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008e: stelem.ref IL_008f: dup IL_0090: ldc.i4.1 IL_0091: ldc.i4.1 IL_0092: ldnull IL_0093: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0098: stelem.ref IL_0099: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009e: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00a8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00ad: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, char> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>>.Target"" IL_00b2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, char>> C.<>o__5.<>p__1"" IL_00b7: ldsfld ""dynamic C.d"" IL_00bc: ldsfld ""char C.Char"" IL_00c1: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, char>.Invoke(System.Runtime.CompilerServices.CallSite, object, char)"" IL_00c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_00cb: brtrue.s IL_010b IL_00cd: ldc.i4 0x100 IL_00d2: ldstr ""f"" IL_00d7: ldnull IL_00d8: ldtoken ""C"" IL_00dd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00e2: ldc.i4.2 IL_00e3: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00e8: dup IL_00e9: ldc.i4.0 IL_00ea: ldc.i4.0 IL_00eb: ldnull IL_00ec: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f1: stelem.ref IL_00f2: dup IL_00f3: ldc.i4.1 IL_00f4: ldc.i4.1 IL_00f5: ldnull IL_00f6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00fb: stelem.ref IL_00fc: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0101: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0106: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_010b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_0110: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_0115: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__5.<>p__2"" IL_011a: ldsfld ""dynamic C.d"" IL_011f: ldsfld ""C C.c"" IL_0124: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object, C)"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_012e: brtrue.s IL_016e IL_0130: ldc.i4 0x100 IL_0135: ldstr ""f"" IL_013a: ldnull IL_013b: ldtoken ""C"" IL_0140: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0145: ldc.i4.2 IL_0146: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_014b: dup IL_014c: ldc.i4.0 IL_014d: ldc.i4.0 IL_014e: ldnull IL_014f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0154: stelem.ref IL_0155: dup IL_0156: ldc.i4.1 IL_0157: ldc.i4.1 IL_0158: ldnull IL_0159: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_015e: stelem.ref IL_015f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0164: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0169: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_016e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_0173: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0178: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__3"" IL_017d: ldsfld ""dynamic C.d"" IL_0182: ldsfld ""object C.obj"" IL_0187: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_018c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_0191: brtrue.s IL_01d1 IL_0193: ldc.i4 0x100 IL_0198: ldstr ""f"" IL_019d: ldnull IL_019e: ldtoken ""C"" IL_01a3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01a8: ldc.i4.2 IL_01a9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ae: dup IL_01af: ldc.i4.0 IL_01b0: ldc.i4.0 IL_01b1: ldnull IL_01b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01b7: stelem.ref IL_01b8: dup IL_01b9: ldc.i4.1 IL_01ba: ldc.i4.0 IL_01bb: ldnull IL_01bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c1: stelem.ref IL_01c2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c7: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01cc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01d6: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__4"" IL_01e0: ldsfld ""dynamic C.d"" IL_01e5: ldsfld ""dynamic C.d"" IL_01ea: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01ef: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_01f4: brtrue.s IL_0234 IL_01f6: ldc.i4 0x100 IL_01fb: ldstr ""f"" IL_0200: ldnull IL_0201: ldtoken ""C"" IL_0206: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_020b: ldc.i4.2 IL_020c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0211: dup IL_0212: ldc.i4.0 IL_0213: ldc.i4.0 IL_0214: ldnull IL_0215: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_021a: stelem.ref IL_021b: dup IL_021c: ldc.i4.1 IL_021d: ldc.i4.2 IL_021e: ldnull IL_021f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0224: stelem.ref IL_0225: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_022a: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_022f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0234: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0239: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_023e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__5.<>p__5"" IL_0243: ldsfld ""dynamic C.d"" IL_0248: ldnull IL_0249: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_024e: ret } "); } [Fact] public void InvokeMember_UseCompileTimeType_ConvertedReceiver() { string source = @" class C { void M(object o) { (o as dynamic).f(); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 81 (0x51) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.1 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_0040: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object>> C.<>o__0.<>p__0"" IL_004a: ldarg.1 IL_004b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0050: ret } "); } [Fact] public void InvokeMember_Dynamic_Generic() { string source = @" public class C { public dynamic M(dynamic d) { return d.m<C, int>(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 119 (0x77) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0060 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldc.i4.2 IL_000e: newarr ""System.Type"" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: stelem.ref IL_0020: dup IL_0021: ldc.i4.1 IL_0022: ldtoken ""int"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: stelem.ref IL_002d: ldtoken ""C"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: ldc.i4.2 IL_0038: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003d: dup IL_003e: ldc.i4.0 IL_003f: ldc.i4.0 IL_0040: ldnull IL_0041: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0046: stelem.ref IL_0047: dup IL_0048: ldc.i4.1 IL_0049: ldc.i4.0 IL_004a: ldnull IL_004b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0050: stelem.ref IL_0051: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0056: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0060: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0065: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_006f: ldarg.1 IL_0070: ldarg.1 IL_0071: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0076: ret } "); } [Fact] public void InvokeMember_Static_Generic() { string source = @" public class C { public dynamic M(C c, dynamic d) { return c.F<int, dynamic>(null, this, d); } public int F<T1, T2>(C a, C b, double c) { return 1; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 141 (0x8d) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0074 IL_0007: ldc.i4.0 IL_0008: ldstr ""F"" IL_000d: ldc.i4.2 IL_000e: newarr ""System.Type"" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldtoken ""int"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: stelem.ref IL_0020: dup IL_0021: ldc.i4.1 IL_0022: ldtoken ""object"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: stelem.ref IL_002d: ldtoken ""C"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: ldc.i4.4 IL_0038: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003d: dup IL_003e: ldc.i4.0 IL_003f: ldc.i4.1 IL_0040: ldnull IL_0041: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0046: stelem.ref IL_0047: dup IL_0048: ldc.i4.1 IL_0049: ldc.i4.2 IL_004a: ldnull IL_004b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0050: stelem.ref IL_0051: dup IL_0052: ldc.i4.2 IL_0053: ldc.i4.1 IL_0054: ldnull IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: dup IL_005c: ldc.i4.3 IL_005d: ldc.i4.0 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0079: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>> C.<>o__0.<>p__0"" IL_0083: ldarg.1 IL_0084: ldnull IL_0085: ldarg.0 IL_0086: ldarg.2 IL_0087: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, C, object)"" IL_008c: ret } "); } [Fact] public void InvokeMember_Dynamic_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d, int a) { return d.m(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 123 (0x7b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0061 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.4 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.4 IL_002b: ldstr ""goo"" IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.5 IL_0039: ldstr ""bar"" IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.7 IL_0047: ldstr ""baz"" IL_004c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0051: stelem.ref IL_0052: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0057: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0061: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0066: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Target"" IL_006b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0070: ldarg.1 IL_0071: ldarg.1 IL_0072: ldarg.2 IL_0073: ldc.i4.s 123 IL_0075: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_007a: ret } "); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void InvokeMember_NamedArguments_PartialMethods() { string source = @" partial class C { static partial void F(int i); } partial class C { static partial void F(int j) { System.Console.WriteLine(j); } public static void Main() { dynamic d = 2; F(i: d); } } "; CompileAndVerifyWithCSharp(source, expectedOutput: "2"); } [Fact] public void InvokeMember_ManyArgs_F14() { string source = @" public class C { public dynamic M14(dynamic d) { return d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); } }"; CompileAndVerifyIL(source, "C.M14", @" { // Code size 247 (0xf7) .maxstack 17 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00cd IL_000a: ldc.i4.0 IL_000b: ldstr ""m"" IL_0010: ldnull IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.s 15 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.3 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: dup IL_004b: ldc.i4.4 IL_004c: ldc.i4.3 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.5 IL_0056: ldc.i4.3 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.6 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.7 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.8 IL_0074: ldc.i4.3 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.s 9 IL_007f: ldc.i4.3 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.s 10 IL_008a: ldc.i4.3 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.s 11 IL_0095: ldc.i4.3 IL_0096: ldnull IL_0097: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009c: stelem.ref IL_009d: dup IL_009e: ldc.i4.s 12 IL_00a0: ldc.i4.3 IL_00a1: ldnull IL_00a2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a7: stelem.ref IL_00a8: dup IL_00a9: ldc.i4.s 13 IL_00ab: ldc.i4.3 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.s 14 IL_00b6: ldc.i4.3 IL_00b7: ldnull IL_00b8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bd: stelem.ref IL_00be: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00cd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Target"" IL_00d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00dc: ldarg.1 IL_00dd: ldc.i4.1 IL_00de: ldc.i4.2 IL_00df: ldc.i4.3 IL_00e0: ldc.i4.4 IL_00e1: ldc.i4.5 IL_00e2: ldc.i4.6 IL_00e3: ldc.i4.7 IL_00e4: ldc.i4.8 IL_00e5: ldc.i4.s 9 IL_00e7: ldc.i4.s 10 IL_00e9: ldc.i4.s 11 IL_00eb: ldc.i4.s 12 IL_00ed: ldc.i4.s 13 IL_00ef: ldc.i4.s 14 IL_00f1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00f6: ret }"); } [Fact] public void InvokeMember_ManyArgs_F15() { // TODO: verify metadata of the synthesized delegate // TODO: use VerifyRealIL to check that dynamic is erased string source = @" public class C { public dynamic M15(dynamic d) { return d.m(1, true, 1.0, 'c', ""s"", (byte)1, (sbyte)1, (uint)1, (long)1, (ulong)1, (float)1.0, (decimal)1, default(System.DateTime), d, d); } }"; CompileAndVerifyIL(source, "C.M15", @" { // Code size 284 (0x11c) .maxstack 18 .locals init (System.DateTime V_0) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d8 IL_000a: ldc.i4.0 IL_000b: ldstr ""m"" IL_0010: ldnull IL_0011: ldtoken ""C"" IL_0016: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001b: ldc.i4.s 16 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.2 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: dup IL_0041: ldc.i4.3 IL_0042: ldc.i4.3 IL_0043: ldnull IL_0044: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0049: stelem.ref IL_004a: dup IL_004b: ldc.i4.4 IL_004c: ldc.i4.3 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.5 IL_0056: ldc.i4.3 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.6 IL_0060: ldc.i4.3 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.7 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: dup IL_0073: ldc.i4.8 IL_0074: ldc.i4.3 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.s 9 IL_007f: ldc.i4.3 IL_0080: ldnull IL_0081: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0086: stelem.ref IL_0087: dup IL_0088: ldc.i4.s 10 IL_008a: ldc.i4.3 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: dup IL_0093: ldc.i4.s 11 IL_0095: ldc.i4.3 IL_0096: ldnull IL_0097: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009c: stelem.ref IL_009d: dup IL_009e: ldc.i4.s 12 IL_00a0: ldc.i4.3 IL_00a1: ldnull IL_00a2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a7: stelem.ref IL_00a8: dup IL_00a9: ldc.i4.s 13 IL_00ab: ldc.i4.1 IL_00ac: ldnull IL_00ad: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b2: stelem.ref IL_00b3: dup IL_00b4: ldc.i4.s 14 IL_00b6: ldc.i4.0 IL_00b7: ldnull IL_00b8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bd: stelem.ref IL_00be: dup IL_00bf: ldc.i4.s 15 IL_00c1: ldc.i4.0 IL_00c2: ldnull IL_00c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c8: stelem.ref IL_00c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00ce: call ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d3: stsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00d8: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00dd: ldfld ""<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>>.Target"" IL_00e2: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>> C.<>o__0.<>p__0"" IL_00e7: ldarg.1 IL_00e8: ldc.i4.1 IL_00e9: ldc.i4.1 IL_00ea: ldc.r8 1 IL_00f3: ldc.i4.s 99 IL_00f5: ldstr ""s"" IL_00fa: ldc.i4.1 IL_00fb: ldc.i4.1 IL_00fc: ldc.i4.1 IL_00fd: ldc.i4.1 IL_00fe: conv.i8 IL_00ff: ldc.i4.1 IL_0100: conv.i8 IL_0101: ldc.r4 1 IL_0106: ldsfld ""decimal decimal.One"" IL_010b: ldloca.s V_0 IL_010d: initobj ""System.DateTime"" IL_0113: ldloc.0 IL_0114: ldarg.1 IL_0115: ldarg.1 IL_0116: callvirt ""object <>F<System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, bool, double, char, string, byte, sbyte, uint, long, ulong, float, decimal, System.DateTime, object, object)"" IL_011b: ret } " ); } [Fact] public void InvokeMember_ManyArgs_A14() { string source = @" public class C { public void M14(dynamic d) { d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); } }"; CompileAndVerifyIL(source, "C.M14", @" { // Code size 251 (0xfb) .maxstack 17 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d1 IL_000a: ldc.i4 0x100 IL_000f: ldstr ""m"" IL_0014: ldnull IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.s 15 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.4 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.5 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.6 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.7 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.8 IL_0078: ldc.i4.3 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: dup IL_0081: ldc.i4.s 9 IL_0083: ldc.i4.3 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.s 10 IL_008e: ldc.i4.3 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: dup IL_0097: ldc.i4.s 11 IL_0099: ldc.i4.3 IL_009a: ldnull IL_009b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a0: stelem.ref IL_00a1: dup IL_00a2: ldc.i4.s 12 IL_00a4: ldc.i4.3 IL_00a5: ldnull IL_00a6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ab: stelem.ref IL_00ac: dup IL_00ad: ldc.i4.s 13 IL_00af: ldc.i4.3 IL_00b0: ldnull IL_00b1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b6: stelem.ref IL_00b7: dup IL_00b8: ldc.i4.s 14 IL_00ba: ldc.i4.3 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c7: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00d6: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Target"" IL_00db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00e0: ldarg.1 IL_00e1: ldc.i4.1 IL_00e2: ldc.i4.2 IL_00e3: ldc.i4.3 IL_00e4: ldc.i4.4 IL_00e5: ldc.i4.5 IL_00e6: ldc.i4.6 IL_00e7: ldc.i4.7 IL_00e8: ldc.i4.8 IL_00e9: ldc.i4.s 9 IL_00eb: ldc.i4.s 10 IL_00ed: ldc.i4.s 11 IL_00ef: ldc.i4.s 12 IL_00f1: ldc.i4.s 13 IL_00f3: ldc.i4.s 14 IL_00f5: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00fa: ret } "); } [Fact] public void InvokeMember_ManyArgs_A15() { string source = @" public class C { public void M15(dynamic d) { d.m(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); } }"; CompileAndVerifyIL(source, "C.M15", @" { // Code size 264 (0x108) .maxstack 18 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00dc IL_000a: ldc.i4 0x100 IL_000f: ldstr ""m"" IL_0014: ldnull IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.s 16 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.2 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.3 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.4 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.5 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.6 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.7 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.8 IL_0078: ldc.i4.3 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: dup IL_0081: ldc.i4.s 9 IL_0083: ldc.i4.3 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: dup IL_008c: ldc.i4.s 10 IL_008e: ldc.i4.3 IL_008f: ldnull IL_0090: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0095: stelem.ref IL_0096: dup IL_0097: ldc.i4.s 11 IL_0099: ldc.i4.3 IL_009a: ldnull IL_009b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a0: stelem.ref IL_00a1: dup IL_00a2: ldc.i4.s 12 IL_00a4: ldc.i4.3 IL_00a5: ldnull IL_00a6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ab: stelem.ref IL_00ac: dup IL_00ad: ldc.i4.s 13 IL_00af: ldc.i4.3 IL_00b0: ldnull IL_00b1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b6: stelem.ref IL_00b7: dup IL_00b8: ldc.i4.s 14 IL_00ba: ldc.i4.3 IL_00bb: ldnull IL_00bc: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c1: stelem.ref IL_00c2: dup IL_00c3: ldc.i4.s 15 IL_00c5: ldc.i4.3 IL_00c6: ldnull IL_00c7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cc: stelem.ref IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00e1: ldfld ""<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int> System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>> C.<>o__0.<>p__0"" IL_00eb: ldarg.1 IL_00ec: ldc.i4.1 IL_00ed: ldc.i4.2 IL_00ee: ldc.i4.3 IL_00ef: ldc.i4.4 IL_00f0: ldc.i4.5 IL_00f1: ldc.i4.6 IL_00f2: ldc.i4.7 IL_00f3: ldc.i4.8 IL_00f4: ldc.i4.s 9 IL_00f6: ldc.i4.s 10 IL_00f8: ldc.i4.s 11 IL_00fa: ldc.i4.s 12 IL_00fc: ldc.i4.s 13 IL_00fe: ldc.i4.s 14 IL_0100: ldc.i4.s 15 IL_0102: callvirt ""void <>A<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_0107: ret } "); } [Fact] public void InvokeMember_ByRefArgs() { string source = @" public class C { public dynamic M(dynamic d) { return d.m(ref d, out d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_004d IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.3 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.1 IL_002a: ldc.i4.s 9 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: dup IL_0034: ldc.i4.2 IL_0035: ldc.i4.s 17 IL_0037: ldnull IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0043: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0048: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_004d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_0052: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_0057: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_005c: ldarg.1 IL_005d: ldarga.s V_1 IL_005f: ldarga.s V_1 IL_0061: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref object)"" IL_0066: ret } "); } [Fact] public void InvokeMember_ByRefArgs_Runtime() { string source = @" public class C { public static dynamic d = new C(); public static void Main() { d.m(ref d, out d); } public void m(ref object a, out object b) { b = null; } } "; CompileAndVerifyWithCSharp(source, expectedOutput: ""); } /// <summary> /// By-ref dynamic argument doesn't make the call dynamic. /// </summary> [Fact] public void InvokeMember_ByRefDynamic() { string source = @" public class C { static dynamic d = true; public static void f(ref dynamic d) { } public static void M() { f(ref d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldsflda ""dynamic C.d"" IL_0005: call ""void C.f(ref dynamic)"" IL_000a: ret } "); } /// <summary> /// ref/out can be omitted at call-site. /// </summary> [Fact] public void InvokeMember_CallSiteRefOutOmitted() { string source = @" public class C { dynamic d = true; public void f(ref int a, out int b, ref dynamic c, out object d) { b = 1; d = null; } public void M() { object lo = null; dynamic ld; f(d, d, ref lo, out ld); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 141 (0x8d) .maxstack 9 .locals init (object V_0, //lo object V_1) //ld IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0007: brtrue.s IL_0067 IL_0009: ldc.i4 0x102 IL_000e: ldstr ""f"" IL_0013: ldnull IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.5 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: dup IL_0039: ldc.i4.2 IL_003a: ldc.i4.0 IL_003b: ldnull IL_003c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldc.i4.s 9 IL_0046: ldnull IL_0047: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004c: stelem.ref IL_004d: dup IL_004e: ldc.i4.4 IL_004f: ldc.i4.s 17 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_005d: call ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0062: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0067: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_006c: ldfld ""<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>>.Target"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>> C.<>o__2.<>p__0"" IL_0076: ldarg.0 IL_0077: ldarg.0 IL_0078: ldfld ""dynamic C.d"" IL_007d: ldarg.0 IL_007e: ldfld ""dynamic C.d"" IL_0083: ldloca.s V_0 IL_0085: ldloca.s V_1 IL_0087: callvirt ""void <>A{00000500}<System.Runtime.CompilerServices.CallSite, C, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object, object, ref object, ref object)"" IL_008c: ret } "); } [Fact] public void InvokeStaticMember1() { string source = @" public class C { public void M(dynamic d) { D.F(d); } } public class D { public static void F(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""F"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0055: ldtoken ""D"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.1 IL_0060: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0065: ret }"); } [Fact] public void InvokeStaticMember2() { string source = @" public class C { static dynamic d = true; public static void f(dynamic d) { } public static void M() { f(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""f"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__2.<>p__0"" IL_0055: ldtoken ""C"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.d"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_0069: ret } "); } [Fact] [WorkItem(627091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627091")] public void InvokeStaticMember_InLambda() { string source = @" class C { static void Goo(dynamic x) { System.Action a = () => Goo(x); } } "; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0.<Goo>b__0", @" { // Code size 107 (0x6b) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0055: ldtoken ""C"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0065: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_006a: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Local() { string source = @" public class C { public void M(dynamic d) { S s = new S(); s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 102 (0x66) .maxstack 9 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_000d: brtrue.s IL_004e IL_000f: ldc.i4 0x100 IL_0014: ldstr ""goo"" IL_0019: ldnull IL_001a: ldtoken ""C"" IL_001f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0024: ldc.i4.2 IL_0025: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldc.i4.s 9 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: dup IL_0036: ldc.i4.1 IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003e: stelem.ref IL_003f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0044: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0049: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0053: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0058: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_005d: ldloca.s V_0 IL_005f: ldarg.1 IL_0060: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0065: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Parameter() { string source = @" public class C { public void M(S s, dynamic d) { s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 94 (0x5e) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0055: ldarga.s V_1 IL_0057: ldarg.2 IL_0058: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_005d: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_This() { string source = @" public struct S { int a; public void M(dynamic d) { this.Equals(d); } } "; CompileAndVerifyIL(source, "S.M", @" { // Code size 93 (0x5d) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Equals"" IL_0011: ldnull IL_0012: ldtoken ""S"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> S.<>o__1.<>p__0"" IL_0055: ldarg.0 IL_0056: ldarg.1 IL_0057: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_005c: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_FieldAccess() { string source = @" public class C { private S s; public void M(dynamic d) { s.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0054: ldarg.0 IL_0055: ldfld ""S C.s"" IL_005a: ldarg.1 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_ArrayAccess() { string source = @" public class C { private S[] s; public void M(dynamic d) { s[0].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_004b: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0055: ldarg.0 IL_0056: ldfld ""S[] C.s"" IL_005b: ldc.i4.0 IL_005c: ldelema ""S"" IL_0061: ldarg.1 IL_0062: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0067: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerIndirectionOperator1() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S s = new S(); S* ptr = &s; (*ptr).goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 105 (0x69) .maxstack 9 .locals init (S V_0, //s S* V_1) //ptr IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: stloc.1 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.1 IL_0062: ldarg.1 IL_0063: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0068: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerIndirectionOperator2() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S s = new S(); S* ptr = &s; ptr->goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 105 (0x69) .maxstack 9 .locals init (S V_0, //s S* V_1) //ptr IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: stloc.1 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.1 IL_0062: ldarg.1 IL_0063: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_0068: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_PointerElementAccess() { string source = @" public unsafe class C { private S s; public void M(dynamic d) { S* ptr = stackalloc S[2]; ptr[1].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 112 (0x70) .maxstack 9 .locals init (S* V_0) //ptr IL_0000: ldc.i4.2 IL_0001: conv.u IL_0002: sizeof ""S"" IL_0008: mul.ovf.un IL_0009: localloc IL_000b: stloc.0 IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0011: brtrue.s IL_0052 IL_0013: ldc.i4 0x100 IL_0018: ldstr ""goo"" IL_001d: ldnull IL_001e: ldtoken ""C"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: ldc.i4.2 IL_0029: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002e: dup IL_002f: ldc.i4.0 IL_0030: ldc.i4.s 9 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: dup IL_003a: ldc.i4.1 IL_003b: ldc.i4.0 IL_003c: ldnull IL_003d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0042: stelem.ref IL_0043: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0048: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0057: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__1.<>p__0"" IL_0061: ldloc.0 IL_0062: sizeof ""S"" IL_0068: add IL_0069: ldarg.1 IL_006a: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object)"" IL_006f: ret } ", allowUnsafe: true, verify: Verification.Fails); } [Fact] public void InvokeMember_ValueTypeReceiver_TypeReference() { string source = @" using System; public class C { public void M(dynamic d) { int a = 1; TypedReference tr = __makeref(a); __refvalue(tr, int).Equals(d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 108 (0x6c) .maxstack 9 .locals init (int V_0, //a System.TypedReference V_1) //tr IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: stloc.1 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_000f: brtrue.s IL_0050 IL_0011: ldc.i4 0x100 IL_0016: ldstr ""Equals"" IL_001b: ldnull IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.2 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.s 9 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.1 IL_0039: ldc.i4.0 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0046: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004b: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_0055: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>>.Target"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>> C.<>o__0.<>p__0"" IL_005f: ldloc.1 IL_0060: refanyval ""int"" IL_0065: ldarg.1 IL_0066: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref int, object)"" IL_006b: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_Literal() { string source = @" public class C { public void M(dynamic d) { ""a"".Equals(d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 96 (0x60) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Equals"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, string, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, string, object>> C.<>o__0.<>p__0"" IL_0054: ldstr ""a"" IL_0059: ldarg.1 IL_005a: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, string, object>.Invoke(System.Runtime.CompilerServices.CallSite, string, object)"" IL_005f: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_Assignment() { string source = @" public class C { public void M(dynamic d, S s, S t) { (s = t).goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 95 (0x5f) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.3 IL_0055: dup IL_0056: starg.s V_2 IL_0058: ldarg.1 IL_0059: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_005e: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_PropertyAccess() { string source = @" public class C { private S P { get; set; } public void M(C c, dynamic d) { c.P.goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__4.<>p__0"" IL_0054: ldarg.1 IL_0055: callvirt ""S C.P.get"" IL_005a: ldarg.2 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret } "); } [Fact] public void InvokeMember_ValueTypeReceiver_IndexerAccess() { string source = @" public class C { private S this[int index] { get { return new S(); } set { } } public void M(C c, dynamic d) { c[0].goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 98 (0x62) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__3.<>p__0"" IL_0054: ldarg.1 IL_0055: ldc.i4.0 IL_0056: callvirt ""S C.this[int].get"" IL_005b: ldarg.2 IL_005c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0061: ret }"); } [Fact] public void InvokeMember_ValueTypeReceiver_Invocation() { string source = @" public class C { public void M(System.Func<S> f, dynamic d) { f().goo(d); } } public struct S { public int X; public void goo(int a) {} } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 97 (0x61) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_004a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, S, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, S, object>> C.<>o__0.<>p__0"" IL_0054: ldarg.1 IL_0055: callvirt ""S System.Func<S>.Invoke()"" IL_005a: ldarg.2 IL_005b: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, S, object>.Invoke(System.Runtime.CompilerServices.CallSite, S, object)"" IL_0060: ret }"); } [Fact] public void InvokeMember_InvokeMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.f().g(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 152 (0x98) .maxstack 11 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""g"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004b: brtrue.s IL_007d IL_004d: ldc.i4.0 IL_004e: ldstr ""f"" IL_0053: ldnull IL_0054: ldtoken ""C"" IL_0059: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005e: ldc.i4.1 IL_005f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0064: dup IL_0065: ldc.i4.0 IL_0066: ldc.i4.0 IL_0067: ldnull IL_0068: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006d: stelem.ref IL_006e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0073: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0078: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0082: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0087: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008c: ldarg.1 IL_008d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0092: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0097: ret }"); } [Fact] public void InvokeConstructor() { string source = @" public class C { public D M(dynamic d) { return new D(d); } } public class D { public D(int x) {} public D(string x) {} public D(string x, string y) {} }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.s 33 IL_001c: ldnull IL_001d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0022: stelem.ref IL_0023: dup IL_0024: ldc.i4.1 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeConstructor(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_0041: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>> C.<>o__0.<>p__0"" IL_004b: ldtoken ""D"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: ldarg.1 IL_0056: callvirt ""D System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, D>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_005b: ret } "); } [Fact] public void Invoke_Dynamic() { string source = @" public class C { public dynamic M(dynamic d, int a) { return d(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 117 (0x75) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_005b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.4 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.4 IL_0025: ldstr ""goo"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.5 IL_0033: ldstr ""bar"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.7 IL_0041: ldstr ""baz"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0051: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0056: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_0060: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>>.Target"" IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>> C.<>o__0.<>p__0"" IL_006a: ldarg.1 IL_006b: ldarg.1 IL_006c: ldarg.2 IL_006d: ldc.i4.s 123 IL_006f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_0074: ret } "); } [Fact] public void Invoke_Dynamic_DiscardResult() { string source = @" public class C { public void M(dynamic d, int a) { d(goo: d, bar: a, baz: 123); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 121 (0x79) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_005f IL_0007: ldc.i4 0x100 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.4 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.4 IL_0029: ldstr ""goo"" IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: dup IL_0035: ldc.i4.2 IL_0036: ldc.i4.5 IL_0037: ldstr ""bar"" IL_003c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.3 IL_0044: ldc.i4.7 IL_0045: ldstr ""baz"" IL_004a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004f: stelem.ref IL_0050: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0055: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_005f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_0064: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>>.Target"" IL_0069: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>> C.<>o__0.<>p__0"" IL_006e: ldarg.1 IL_006f: ldarg.1 IL_0070: ldarg.2 IL_0071: ldc.i4.s 123 IL_0073: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, object, int, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, int)"" IL_0078: ret } "); } [Fact] public void Invoke_DynamicMember() { const string source = @" class C { dynamic d = null; void M(C c) { c.d(1); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 91 (0x5b) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_003f IL_0007: ldc.i4 0x100 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.2 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0035: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_0044: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__1.<>p__0"" IL_004e: ldarg.1 IL_004f: ldfld ""dynamic C.d"" IL_0054: ldc.i4.1 IL_0055: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_005a: ret }"); } [Fact] public void Invoke_Static() { string source = @" public delegate int F(int a, bool b, C c); public class C { public dynamic M(F f, dynamic d) { return f(d, d, d); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_004f IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.4 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.3 IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0045: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_0054: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>>.Target"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>> C.<>o__0.<>p__0"" IL_005e: ldarg.1 IL_005f: ldarg.2 IL_0060: ldarg.2 IL_0061: ldarg.2 IL_0062: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, F, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, F, object, object, object)"" IL_0067: ret } "); } [Fact] public void Invoke_Invoke() { string source = @" public class C { public dynamic M(dynamic d) { return d()(); } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 140 (0x8c) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0031 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.1 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0045: brtrue.s IL_0071 IL_0047: ldc.i4.0 IL_0048: ldtoken ""C"" IL_004d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0052: ldc.i4.1 IL_0053: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldc.i4.0 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0080: ldarg.1 IL_0081: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0086: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008b: ret }"); } [Fact] public void TypeInferenceGenericParameterTainting() { string source = @" using System.Collections.Generic; class C { public void F<T>(Dictionary<T, dynamic> d) { } static void M(C c, Dictionary<dynamic, dynamic> d) { c.F(d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""void C.F<object>(System.Collections.Generic.Dictionary<object, dynamic>)"" IL_0007: ret } "); } [Fact] public void InvokeMember_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static object Goo(object x) { return x; } }"; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 168 (0xa8) .maxstack 12 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_007e IL_0043: ldc.i4.0 IL_0044: ldstr ""Goo"" IL_0049: ldnull IL_004a: ldtoken ""C"" IL_004f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0054: ldc.i4.2 IL_0055: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005a: dup IL_005b: ldc.i4.0 IL_005c: ldc.i4.s 33 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: dup IL_0066: ldc.i4.1 IL_0067: ldc.i4.0 IL_0068: ldnull IL_0069: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006e: stelem.ref IL_006f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0074: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0079: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_0083: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>>.Target"" IL_0088: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>> C.<>o__0.<>p__0"" IL_008d: ldtoken ""C"" IL_0092: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0097: ldarg.1 IL_0098: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Type, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_009d: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a2: call ""B..ctor(int)"" IL_00a7: ret } "); } [Fact] public void Invoke_Field_InConstructorInitializer() { string source = @" using System; class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static Action<object> Goo; } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 156 (0x9c) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_0077 IL_0043: ldc.i4.0 IL_0044: ldtoken ""C"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: ldc.i4.2 IL_004f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0054: dup IL_0055: ldc.i4.0 IL_0056: ldc.i4.1 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0072: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0077: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_007c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Target"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0086: ldsfld ""System.Action<object> C.Goo"" IL_008b: ldarg.1 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Action<object>, object)"" IL_0091: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: call ""B..ctor(int)"" IL_009b: ret } "); } [Fact] public void Invoke_Property_InConstructorInitializer() { string source = @" using System; class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)Goo(x)) { } static Action<object> Goo { get; set; } } "; CompileAndVerifyIL(source, "C..ctor", @" { // Code size 156 (0x9c) .maxstack 10 IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""int"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0041: brtrue.s IL_0077 IL_0043: ldc.i4.0 IL_0044: ldtoken ""C"" IL_0049: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004e: ldc.i4.2 IL_004f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0054: dup IL_0055: ldc.i4.0 IL_0056: ldc.i4.1 IL_0057: ldnull IL_0058: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0072: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0077: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_007c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>>.Target"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>> C.<>o__0.<>p__0"" IL_0086: call ""System.Action<object> C.Goo.get"" IL_008b: ldarg.1 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, System.Action<object>, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Action<object>, object)"" IL_0091: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: call ""B..ctor(int)"" IL_009b: ret } "); } #endregion #region GetMember, GetIndex, SetMember, SetIndex [Fact] public void GetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 76 (0x4c) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0045: ldarg.1 IL_0046: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004b: ret } "); } [Fact] public void GetMember_GetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m.n; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 150 (0x96) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""n"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004a: brtrue.s IL_007b IL_004c: ldc.i4.0 IL_004d: ldstr ""m"" IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.1 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0071: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0076: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0080: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008a: ldarg.1 IL_008b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0090: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0095: ret } "); } [Fact] public void GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d[1]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 82 (0x52) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004a: ldarg.1 IL_004b: ldc.i4.1 IL_004c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0051: ret } "); } [Fact] public void GetMember_GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d.m[1]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 157 (0x9d) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_0081 IL_0051: ldc.i4.s 64 IL_0053: ldstr ""m"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.1 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.0 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0090: ldarg.1 IL_0091: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0096: ldc.i4.1 IL_0097: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_009c: ret } "); } [Fact] public void GetIndex_GetIndex() { string source = @" public class C { public dynamic M(dynamic d) { return d[1][2]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 162 (0xa2) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_0085 IL_0051: ldc.i4.0 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.2 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0080: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0085: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_008a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__0"" IL_0094: ldarg.1 IL_0095: ldc.i4.1 IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_009b: ldc.i4.2 IL_009c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00a1: ret } "); } [Fact] public void GetIndex_ManyArgs_F15() { string source = @" public class C { public dynamic M(dynamic d) { return d[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 254 (0xfe) .maxstack 18 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_0005: brtrue IL_00d2 IL_000a: ldc.i4.0 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldc.i4.s 16 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.3 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.3 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: dup IL_003b: ldc.i4.3 IL_003c: ldc.i4.3 IL_003d: ldnull IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0043: stelem.ref IL_0044: dup IL_0045: ldc.i4.4 IL_0046: ldc.i4.3 IL_0047: ldnull IL_0048: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004d: stelem.ref IL_004e: dup IL_004f: ldc.i4.5 IL_0050: ldc.i4.3 IL_0051: ldnull IL_0052: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.6 IL_005a: ldc.i4.3 IL_005b: ldnull IL_005c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0061: stelem.ref IL_0062: dup IL_0063: ldc.i4.7 IL_0064: ldc.i4.3 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.8 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.s 9 IL_0079: ldc.i4.3 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.s 10 IL_0084: ldc.i4.3 IL_0085: ldnull IL_0086: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008b: stelem.ref IL_008c: dup IL_008d: ldc.i4.s 11 IL_008f: ldc.i4.3 IL_0090: ldnull IL_0091: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0096: stelem.ref IL_0097: dup IL_0098: ldc.i4.s 12 IL_009a: ldc.i4.3 IL_009b: ldnull IL_009c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a1: stelem.ref IL_00a2: dup IL_00a3: ldc.i4.s 13 IL_00a5: ldc.i4.3 IL_00a6: ldnull IL_00a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ac: stelem.ref IL_00ad: dup IL_00ae: ldc.i4.s 14 IL_00b0: ldc.i4.3 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: dup IL_00b9: ldc.i4.s 15 IL_00bb: ldc.i4.3 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cd: stsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00d7: ldfld ""<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object> System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>>.Target"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>> C.<>o__0.<>p__0"" IL_00e1: ldarg.1 IL_00e2: ldc.i4.1 IL_00e3: ldc.i4.2 IL_00e4: ldc.i4.3 IL_00e5: ldc.i4.4 IL_00e6: ldc.i4.5 IL_00e7: ldc.i4.6 IL_00e8: ldc.i4.7 IL_00e9: ldc.i4.8 IL_00ea: ldc.i4.s 9 IL_00ec: ldc.i4.s 10 IL_00ee: ldc.i4.s 11 IL_00f0: ldc.i4.s 12 IL_00f2: ldc.i4.s 13 IL_00f4: ldc.i4.s 14 IL_00f6: ldc.i4.s 15 IL_00f8: callvirt ""object <>F<System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)"" IL_00fd: ret } "); } [Fact] public void GetIndex_ByRef() { string source = @" public class C { public dynamic M(dynamic d) { return d[ref d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 84 (0x54) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_003c IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 9 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0041: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004b: ldarg.1 IL_004c: ldarga.s V_1 IL_004e: callvirt ""object <>F{00000010}<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object)"" IL_0053: ret } "); } [Fact] public void GetIndex_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d) { return d[a: 1, b: d, c: null, d: ref d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 133 (0x85) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_006a IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.5 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.7 IL_0025: ldstr ""a"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.4 IL_0033: ldstr ""b"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.6 IL_0041: ldstr ""c"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: dup IL_004d: ldc.i4.4 IL_004e: ldc.i4.s 13 IL_0050: ldstr ""d"" IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0060: call ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0065: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_006f: ldfld ""<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>>.Target"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0079: ldarg.1 IL_007a: ldc.i4.1 IL_007b: ldarg.1 IL_007c: ldnull IL_007d: ldarga.s V_1 IL_007f: callvirt ""object <>F{00000400}<System.Runtime.CompilerServices.CallSite, object, int, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object, object, ref object)"" IL_0084: ret } "); } [Fact] public void GetIndex_StaticReceiver() { string source = @" public class C { C a, b; int this[int i] { get { return 0; } set { } } public dynamic M(dynamic d) { return a.b[d]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__5.<>p__0"" IL_004a: ldarg.0 IL_004b: ldfld ""C C.a"" IL_0050: ldfld ""C C.b"" IL_0055: ldarg.1 IL_0056: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_005b: ret } "); } [Fact] public void GetIndex_IndexedProperty() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public ReadOnly Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d]; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 167 (0xa7) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_004f: brtrue.s IL_0081 IL_0051: ldc.i4.s 64 IL_0053: ldstr ""IndexedProperty"" IL_0058: ldtoken ""C"" IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0062: ldc.i4.1 IL_0063: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0068: dup IL_0069: ldc.i4.0 IL_006a: ldc.i4.1 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0086: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0090: ldarg.0 IL_0091: ldfld ""B C.b"" IL_0096: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_009b: ldarg.0 IL_009c: ldfld ""dynamic C.d"" IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00a6: ret }"); } [Fact] public void SetIndex_IndexedProperty() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get Set End Set End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d] = 42; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 179 (0xb3) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.3 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.3 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__2.<>p__1"" IL_0054: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0059: brtrue.s IL_008b IL_005b: ldc.i4.s 64 IL_005d: ldstr ""IndexedProperty"" IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.1 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_009a: ldarg.0 IL_009b: ldfld ""B C.b"" IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_00a5: ldarg.0 IL_00a6: ldfld ""dynamic C.d"" IL_00ab: ldc.i4.s 42 IL_00ad: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_00b2: ret }"); } [Fact] public void SetIndex_IndexedProperty_CompoundAssignment() { string vbSource = @" Imports System.Runtime.InteropServices <ComImport, Guid(""0002095E-0000-0000-C000-000000000046"")> Public Class B Public Property IndexedProperty(arg As Integer) As Integer Get Return arg End Get Set End Set End Property End Class "; var vb = CreateVisualBasicCompilation(GetUniqueName(), vbSource); var vbRef = vb.EmitToImageReference(); string source = @" class C { B b; dynamic d; object M() { return b.IndexedProperty[d] += 42; } } "; // Dev11 - the receiver of GetMember is typed to Object. That seems like a bug, since InvokeMember on an early bound receiver uses the compile time type. // Roslyn: Use strongly typed receiver. // Note that accessing an indexed property is the only way how to get strongly typed receiver. CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, vbRef }, expectedOptimizedIL: @" { // Code size 424 (0x1a8) .maxstack 16 .locals init (B V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""B C.b"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""dynamic C.d"" IL_000d: stloc.1 IL_000e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0013: brtrue.s IL_0057 IL_0015: ldc.i4 0x80 IL_001a: ldtoken ""C"" IL_001f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0024: ldc.i4.3 IL_0025: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002a: dup IL_002b: ldc.i4.0 IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0033: stelem.ref IL_0034: dup IL_0035: ldc.i4.1 IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.2 IL_0040: ldc.i4.0 IL_0041: ldnull IL_0042: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0047: stelem.ref IL_0048: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_004d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0052: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0057: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_005c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_0061: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__2.<>p__4"" IL_0066: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_006b: brtrue.s IL_009d IL_006d: ldc.i4.s 64 IL_006f: ldstr ""IndexedProperty"" IL_0074: ldtoken ""C"" IL_0079: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007e: ldc.i4.1 IL_007f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0084: dup IL_0085: ldc.i4.0 IL_0086: ldc.i4.1 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_00a2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__3"" IL_00ac: ldloc.0 IL_00ad: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_00b2: ldloc.1 IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00b8: brtrue.s IL_00f0 IL_00ba: ldc.i4.0 IL_00bb: ldc.i4.s 63 IL_00bd: ldtoken ""C"" IL_00c2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c7: ldc.i4.2 IL_00c8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00cd: dup IL_00ce: ldc.i4.0 IL_00cf: ldc.i4.0 IL_00d0: ldnull IL_00d1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d6: stelem.ref IL_00d7: dup IL_00d8: ldc.i4.1 IL_00d9: ldc.i4.3 IL_00da: ldnull IL_00db: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e0: stelem.ref IL_00e1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00e6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00eb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00f0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00f5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00fa: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__2.<>p__2"" IL_00ff: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0104: brtrue.s IL_013a IL_0106: ldc.i4.0 IL_0107: ldtoken ""C"" IL_010c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0111: ldc.i4.2 IL_0112: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0117: dup IL_0118: ldc.i4.0 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: dup IL_0122: ldc.i4.1 IL_0123: ldc.i4.0 IL_0124: ldnull IL_0125: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012a: stelem.ref IL_012b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0130: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0135: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_013f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0144: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_014e: brtrue.s IL_0180 IL_0150: ldc.i4.s 64 IL_0152: ldstr ""IndexedProperty"" IL_0157: ldtoken ""C"" IL_015c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0161: ldc.i4.1 IL_0162: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0167: dup IL_0168: ldc.i4.0 IL_0169: ldc.i4.1 IL_016a: ldnull IL_016b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0170: stelem.ref IL_0171: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0176: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_017b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0180: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_0185: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>>.Target"" IL_018a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object>> C.<>o__2.<>p__0"" IL_018f: ldloc.0 IL_0190: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object>.Invoke(System.Runtime.CompilerServices.CallSite, B)"" IL_0195: ldloc.1 IL_0196: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_019b: ldc.i4.s 42 IL_019d: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_01a7: ret } "); } [Fact] public void GetIndex_IndexerWithByRefParam() { var ilRef = MetadataReference.CreateFromImage(TestResources.MetadataTests.Interop.IndexerWithByRefParam.AsImmutableOrNull()); string source = @" class C { B b; dynamic d; object M() { return b[d]; } } "; CompileAndVerifyIL(source, "C.M", references: new MetadataReference[] { SystemCoreRef, CSharpRef, ilRef }, expectedOptimizedIL: @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, B, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>> C.<>o__2.<>p__0"" IL_004a: ldarg.0 IL_004b: ldfld ""B C.b"" IL_0050: ldarg.0 IL_0051: ldfld ""dynamic C.d"" IL_0056: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, B, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, B, object)"" IL_005b: ret } "); } [Fact] public void SetIndex_SetIndex_Receiver() { string source = @" public class C { public dynamic M(dynamic d) { return (d[1] = d)[2]; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 173 (0xad) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_003b IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.2 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.3 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0031: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0036: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_0040: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__0.<>p__1"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_004f: brtrue.s IL_008f IL_0051: ldc.i4.0 IL_0052: ldtoken ""C"" IL_0057: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005c: ldc.i4.3 IL_005d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0062: dup IL_0063: ldc.i4.0 IL_0064: ldc.i4.0 IL_0065: ldnull IL_0066: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006b: stelem.ref IL_006c: dup IL_006d: ldc.i4.1 IL_006e: ldc.i4.3 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.2 IL_0078: ldc.i4.0 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0085: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_0094: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>>.Target"" IL_0099: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>> C.<>o__0.<>p__0"" IL_009e: ldarg.1 IL_009f: ldc.i4.1 IL_00a0: ldarg.1 IL_00a1: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, object)"" IL_00a6: ldc.i4.2 IL_00a7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00ac: ret } "); } [Fact] public void SetIndex_SetIndex_Argument() { string source = @" public class C { public dynamic M(dynamic d) { return d[d[d] = d] = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 184 (0xb8) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0045 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.3 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.2 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__1"" IL_0054: ldarg.1 IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_005a: brtrue.s IL_009a IL_005c: ldc.i4.0 IL_005d: ldtoken ""C"" IL_0062: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0067: ldc.i4.3 IL_0068: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006d: dup IL_006e: ldc.i4.0 IL_006f: ldc.i4.0 IL_0070: ldnull IL_0071: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0076: stelem.ref IL_0077: dup IL_0078: ldc.i4.1 IL_0079: ldc.i4.0 IL_007a: ldnull IL_007b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0080: stelem.ref IL_0081: dup IL_0082: ldc.i4.2 IL_0083: ldc.i4.0 IL_0084: ldnull IL_0085: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008a: stelem.ref IL_008b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0090: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0095: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_009f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>>.Target"" IL_00a4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>> C.<>o__0.<>p__0"" IL_00a9: ldarg.1 IL_00aa: ldarg.1 IL_00ab: ldarg.1 IL_00ac: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_00b1: ldarg.1 IL_00b2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, object)"" IL_00b7: ret } "); } [Fact] public void SetIndex_NamedArguments() { string source = @" public class C { public dynamic M(dynamic d) { return d[a: d, b: 0, c: null, d: out d] = null; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 144 (0x90) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0074 IL_0007: ldc.i4.0 IL_0008: ldtoken ""C"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldc.i4.6 IL_0013: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0018: dup IL_0019: ldc.i4.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0021: stelem.ref IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.4 IL_0025: ldstr ""a"" IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.2 IL_0032: ldc.i4.7 IL_0033: ldstr ""b"" IL_0038: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003d: stelem.ref IL_003e: dup IL_003f: ldc.i4.3 IL_0040: ldc.i4.6 IL_0041: ldstr ""c"" IL_0046: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004b: stelem.ref IL_004c: dup IL_004d: ldc.i4.4 IL_004e: ldc.i4.s 21 IL_0050: ldstr ""d"" IL_0055: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005a: stelem.ref IL_005b: dup IL_005c: ldc.i4.5 IL_005d: ldc.i4.2 IL_005e: ldnull IL_005f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0064: stelem.ref IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0079: ldfld ""<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>> C.<>o__0.<>p__0"" IL_0083: ldarg.1 IL_0084: ldarg.1 IL_0085: ldc.i4.0 IL_0086: ldnull IL_0087: ldarga.s V_1 IL_0089: ldnull IL_008a: callvirt ""object <>F{00000400}<System.Runtime.CompilerServices.CallSite, object, object, int, object, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object, ref object, object)"" IL_008f: ret } "); } [Fact] public void SetIndex_ValueTypeReceiver_Local() { string source = @" public class C { public void M(dynamic d) { S s = new S(); s[d] = 1; } } public struct S { public int X; public int this[int index] { get { return index; } set { } } } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 104 (0x68) .maxstack 7 .locals init (S V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_000d: brtrue.s IL_004e IL_000f: ldc.i4.0 IL_0010: ldtoken ""C"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: ldc.i4.3 IL_001b: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldc.i4.s 9 IL_0024: ldnull IL_0025: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002a: stelem.ref IL_002b: dup IL_002c: ldc.i4.1 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: dup IL_0036: ldc.i4.2 IL_0037: ldc.i4.3 IL_0038: ldnull IL_0039: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003e: stelem.ref IL_003f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0044: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0049: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_0053: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>>.Target"" IL_0058: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>> C.<>o__0.<>p__0"" IL_005d: ldloca.s V_0 IL_005f: ldarg.1 IL_0060: ldc.i4.1 IL_0061: callvirt ""object <>F{00000004}<System.Runtime.CompilerServices.CallSite, S, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, ref S, object, int)"" IL_0066: pop IL_0067: ret }"); } [Fact] public void SetMember() { string source = @" public class C { public dynamic M(dynamic d) { return d.m = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 87 (0x57) .maxstack 8 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0040 IL_0007: ldc.i4.0 IL_0008: ldstr ""m"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.2 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: dup IL_0028: ldc.i4.1 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0036: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0045: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004f: ldarg.1 IL_0050: ldarg.1 IL_0051: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0056: ret } "); } [Fact] public void SetMember_SetMember() { string source = @" public class C { public dynamic M(dynamic d) { return (d.a = d).b = d; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 172 (0xac) .maxstack 10 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_0040 IL_0007: ldc.i4.0 IL_0008: ldstr ""b"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.2 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: dup IL_0028: ldc.i4.1 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0036: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0045: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0054: brtrue.s IL_008f IL_0056: ldc.i4.0 IL_0057: ldstr ""a"" IL_005c: ldtoken ""C"" IL_0061: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0066: ldc.i4.2 IL_0067: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006c: dup IL_006d: ldc.i4.0 IL_006e: ldc.i4.0 IL_006f: ldnull IL_0070: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0075: stelem.ref IL_0076: dup IL_0077: ldc.i4.1 IL_0078: ldc.i4.0 IL_0079: ldnull IL_007a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007f: stelem.ref IL_0080: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0085: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_008f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0094: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0099: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_009e: ldarg.1 IL_009f: ldarg.1 IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00a5: ldarg.1 IL_00a6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00ab: ret } "); } #endregion #region Assignment [Fact] public void AssignmentRhsConversion() { string source = @" public class C { public void M(dynamic p) { dynamic d = 1; p = 2; d.f = 1.0; p[2] = 'c'; } } "; // Dev11 produces more efficient code, see bug 547265: CompileAndVerifyIL(source, "C.M", @" { // Code size 205 (0xcd) .maxstack 8 .locals init (object V_0) //d IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldc.i4.2 IL_0008: box ""int"" IL_000d: starg.s V_1 IL_000f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_0014: brtrue.s IL_004f IL_0016: ldc.i4.0 IL_0017: ldstr ""f"" IL_001c: ldtoken ""C"" IL_0021: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0026: ldc.i4.2 IL_0027: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: dup IL_0037: ldc.i4.1 IL_0038: ldc.i4.3 IL_0039: ldnull IL_003a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003f: stelem.ref IL_0040: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0045: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_004a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_0054: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, double, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>>.Target"" IL_0059: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>> C.<>o__0.<>p__0"" IL_005e: ldloc.0 IL_005f: ldc.r8 1 IL_0068: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, double, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, double)"" IL_006d: pop IL_006e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_0073: brtrue.s IL_00b3 IL_0075: ldc.i4.0 IL_0076: ldtoken ""C"" IL_007b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0080: ldc.i4.3 IL_0081: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0086: dup IL_0087: ldc.i4.0 IL_0088: ldc.i4.0 IL_0089: ldnull IL_008a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008f: stelem.ref IL_0090: dup IL_0091: ldc.i4.1 IL_0092: ldc.i4.3 IL_0093: ldnull IL_0094: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0099: stelem.ref IL_009a: dup IL_009b: ldc.i4.2 IL_009c: ldc.i4.3 IL_009d: ldnull IL_009e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a3: stelem.ref IL_00a4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00ae: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00b8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>>.Target"" IL_00bd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>> C.<>o__0.<>p__1"" IL_00c2: ldarg.1 IL_00c3: ldc.i4.2 IL_00c4: ldc.i4.s 99 IL_00c6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, char, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int, char)"" IL_00cb: pop IL_00cc: ret } "); } [Fact] public void CompoundDynamicMemberAssignment() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 259 (0x103) .maxstack 13 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_000c: brtrue.s IL_004b IL_000e: ldc.i4 0x80 IL_0013: ldstr ""m"" IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_005a: ldloc.0 IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0060: brtrue.s IL_0098 IL_0062: ldc.i4.0 IL_0063: ldc.i4.s 69 IL_0065: ldtoken ""C"" IL_006a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006f: ldc.i4.2 IL_0070: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0075: dup IL_0076: ldc.i4.0 IL_0077: ldc.i4.0 IL_0078: ldnull IL_0079: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007e: stelem.ref IL_007f: dup IL_0080: ldc.i4.1 IL_0081: ldc.i4.0 IL_0082: ldnull IL_0083: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0088: stelem.ref IL_0089: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_008e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0093: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_009d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00a2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__1"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ac: brtrue.s IL_00dd IL_00ae: ldc.i4.0 IL_00af: ldstr ""m"" IL_00b4: ldtoken ""C"" IL_00b9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00be: ldc.i4.1 IL_00bf: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c4: dup IL_00c5: ldc.i4.0 IL_00c6: ldc.i4.0 IL_00c7: ldnull IL_00c8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cd: stelem.ref IL_00ce: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00e2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_00ec: ldloc.0 IL_00ed: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00f2: ldarg.0 IL_00f3: ldfld ""dynamic C.v"" IL_00f8: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00fd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0102: ret }"); } [Fact] public void CompoundDynamicMemberAssignment_PossibleAddHandler() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m += v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 424 (0x1a8) .maxstack 11 .locals init (object V_0, bool V_1, object V_2, object V_3) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldarg.0 IL_0093: ldfld ""dynamic C.v"" IL_0098: stloc.3 IL_0099: ldloc.1 IL_009a: brtrue IL_014c IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00a4: brtrue.s IL_00e3 IL_00a6: ldc.i4 0x80 IL_00ab: ldstr ""m"" IL_00b0: ldtoken ""C"" IL_00b5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ba: ldc.i4.2 IL_00bb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldc.i4.0 IL_00c3: ldnull IL_00c4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c9: stelem.ref IL_00ca: dup IL_00cb: ldc.i4.1 IL_00cc: ldc.i4.0 IL_00cd: ldnull IL_00ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d3: stelem.ref IL_00d4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00de: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00f2: ldloc.0 IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_00f8: brtrue.s IL_0130 IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.s 63 IL_00fd: ldtoken ""C"" IL_0102: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0107: ldc.i4.2 IL_0108: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_010d: dup IL_010e: ldc.i4.0 IL_010f: ldc.i4.0 IL_0110: ldnull IL_0111: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0116: stelem.ref IL_0117: dup IL_0118: ldc.i4.1 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0126: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0130: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0135: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_013f: ldloc.2 IL_0140: ldloc.3 IL_0141: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0146: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_014b: ret IL_014c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0151: brtrue.s IL_0191 IL_0153: ldc.i4 0x104 IL_0158: ldstr ""add_m"" IL_015d: ldnull IL_015e: ldtoken ""C"" IL_0163: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0168: ldc.i4.2 IL_0169: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_016e: dup IL_016f: ldc.i4.0 IL_0170: ldc.i4.0 IL_0171: ldnull IL_0172: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0177: stelem.ref IL_0178: dup IL_0179: ldc.i4.1 IL_017a: ldc.i4.0 IL_017b: ldnull IL_017c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0181: stelem.ref IL_0182: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0187: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_018c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0196: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_019b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_01a0: ldloc.0 IL_01a1: ldloc.3 IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a7: ret } "); } [Fact] public void CompoundDynamicMemberAssignment_PossibleRemoveHandlerNull() { string source = @" public class C { dynamic d; public void M() { d.m -= null; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 419 (0x1a3) .maxstack 11 .locals init (object V_0, bool V_1, object V_2) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__1.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldloc.1 IL_0093: brtrue IL_0146 IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_009d: brtrue.s IL_00dc IL_009f: ldc.i4 0x80 IL_00a4: ldstr ""m"" IL_00a9: ldtoken ""C"" IL_00ae: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b3: ldc.i4.2 IL_00b4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b9: dup IL_00ba: ldc.i4.0 IL_00bb: ldc.i4.0 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: dup IL_00c4: ldc.i4.1 IL_00c5: ldc.i4.0 IL_00c6: ldnull IL_00c7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00cc: stelem.ref IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__4"" IL_00eb: ldloc.0 IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_00f1: brtrue.s IL_0129 IL_00f3: ldc.i4.0 IL_00f4: ldc.i4.s 73 IL_00f6: ldtoken ""C"" IL_00fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0100: ldc.i4.2 IL_0101: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldc.i4.0 IL_0109: ldnull IL_010a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010f: stelem.ref IL_0110: dup IL_0111: ldc.i4.1 IL_0112: ldc.i4.2 IL_0113: ldnull IL_0114: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0119: stelem.ref IL_011a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_011f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0124: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_012e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0133: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__3"" IL_0138: ldloc.2 IL_0139: ldnull IL_013a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_013f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0144: pop IL_0145: ret IL_0146: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_014b: brtrue.s IL_018b IL_014d: ldc.i4 0x104 IL_0152: ldstr ""remove_m"" IL_0157: ldnull IL_0158: ldtoken ""C"" IL_015d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0162: ldc.i4.2 IL_0163: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0168: dup IL_0169: ldc.i4.0 IL_016a: ldc.i4.0 IL_016b: ldnull IL_016c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0171: stelem.ref IL_0172: dup IL_0173: ldc.i4.1 IL_0174: ldc.i4.2 IL_0175: ldnull IL_0176: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_017b: stelem.ref IL_017c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0181: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0186: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_018b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_0190: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0195: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__2"" IL_019a: ldloc.0 IL_019b: ldnull IL_019c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a1: pop IL_01a2: ret } "); } [Fact] public void CompoundDynamicMemberAssignment_PossibleRemoveHandler() { string source = @" public class C { dynamic d, v; public dynamic M() { return d.m -= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 424 (0x1a8) .maxstack 11 .locals init (object V_0, bool V_1, object V_2, object V_3) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_000c: brtrue.s IL_002d IL_000e: ldc.i4.0 IL_000f: ldstr ""m"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.IsEvent(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__2.<>p__1"" IL_003c: ldloc.0 IL_003d: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: brtrue.s IL_0092 IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_004b: brtrue.s IL_007c IL_004d: ldc.i4.0 IL_004e: ldstr ""m"" IL_0053: ldtoken ""C"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldc.i4.1 IL_005e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0063: dup IL_0064: ldc.i4.0 IL_0065: ldc.i4.0 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_0081: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0086: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__2.<>p__0"" IL_008b: ldloc.0 IL_008c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0091: stloc.2 IL_0092: ldarg.0 IL_0093: ldfld ""dynamic C.v"" IL_0098: stloc.3 IL_0099: ldloc.1 IL_009a: brtrue IL_014c IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00a4: brtrue.s IL_00e3 IL_00a6: ldc.i4 0x80 IL_00ab: ldstr ""m"" IL_00b0: ldtoken ""C"" IL_00b5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ba: ldc.i4.2 IL_00bb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00c0: dup IL_00c1: ldc.i4.0 IL_00c2: ldc.i4.0 IL_00c3: ldnull IL_00c4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c9: stelem.ref IL_00ca: dup IL_00cb: ldc.i4.1 IL_00cc: ldc.i4.0 IL_00cd: ldnull IL_00ce: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d3: stelem.ref IL_00d4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00d9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00de: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00e8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__4"" IL_00f2: ldloc.0 IL_00f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_00f8: brtrue.s IL_0130 IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.s 73 IL_00fd: ldtoken ""C"" IL_0102: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0107: ldc.i4.2 IL_0108: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_010d: dup IL_010e: ldc.i4.0 IL_010f: ldc.i4.0 IL_0110: ldnull IL_0111: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0116: stelem.ref IL_0117: dup IL_0118: ldc.i4.1 IL_0119: ldc.i4.0 IL_011a: ldnull IL_011b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0120: stelem.ref IL_0121: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0126: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0130: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_0135: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_013a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__3"" IL_013f: ldloc.2 IL_0140: ldloc.3 IL_0141: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0146: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_014b: ret IL_014c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0151: brtrue.s IL_0191 IL_0153: ldc.i4 0x104 IL_0158: ldstr ""remove_m"" IL_015d: ldnull IL_015e: ldtoken ""C"" IL_0163: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0168: ldc.i4.2 IL_0169: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_016e: dup IL_016f: ldc.i4.0 IL_0170: ldc.i4.0 IL_0171: ldnull IL_0172: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0177: stelem.ref IL_0178: dup IL_0179: ldc.i4.1 IL_017a: ldc.i4.0 IL_017b: ldnull IL_017c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0181: stelem.ref IL_0182: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0187: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_018c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_0196: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_019b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__2.<>p__2"" IL_01a0: ldloc.0 IL_01a1: ldloc.3 IL_01a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_01a7: ret } "); } [Fact] public void CompoundStaticFieldAssignment() { string source = @" public class C { public dynamic Field; C c; dynamic v; public dynamic M() { return c.Field *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 .locals init (C V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.c"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 69 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__0"" IL_0054: ldloc.0 IL_0055: ldfld ""dynamic C.Field"" IL_005a: ldarg.0 IL_005b: ldfld ""dynamic C.v"" IL_0060: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0065: dup IL_0066: stloc.1 IL_0067: stfld ""dynamic C.Field"" IL_006c: ldloc.1 IL_006d: ret }"); } [Fact] public void CompoundStaticPropertyAssignment() { string source = @" public class C { public dynamic Property { get; set; } C c; dynamic v; public dynamic M() { return c.Property *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 110 (0x6e) .maxstack 9 .locals init (C V_0, object V_1) IL_0000: ldarg.0 IL_0001: ldfld ""C C.c"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 69 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__6.<>p__0"" IL_0054: ldloc.0 IL_0055: callvirt ""dynamic C.Property.get"" IL_005a: ldarg.0 IL_005b: ldfld ""dynamic C.v"" IL_0060: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0065: dup IL_0066: stloc.1 IL_0067: callvirt ""void C.Property.set"" IL_006c: ldloc.1 IL_006d: ret } "); } [Fact] public void CompoundDynamicIndexerAssignment() { string source = @" public class C { public int f() { return 1; } public dynamic M(dynamic d, dynamic i, dynamic v) { return d[i, f()] *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 292 (0x124) .maxstack 14 .locals init (object V_0, object V_1, int V_2) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldarg.2 IL_0003: stloc.1 IL_0004: ldarg.0 IL_0005: call ""int C.f()"" IL_000a: stloc.2 IL_000b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_0010: brtrue.s IL_005e IL_0012: ldc.i4 0x80 IL_0017: ldtoken ""C"" IL_001c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0021: ldc.i4.4 IL_0022: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0027: dup IL_0028: ldc.i4.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0030: stelem.ref IL_0031: dup IL_0032: ldc.i4.1 IL_0033: ldc.i4.0 IL_0034: ldnull IL_0035: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003a: stelem.ref IL_003b: dup IL_003c: ldc.i4.2 IL_003d: ldc.i4.1 IL_003e: ldnull IL_003f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0044: stelem.ref IL_0045: dup IL_0046: ldc.i4.3 IL_0047: ldc.i4.0 IL_0048: ldnull IL_0049: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004e: stelem.ref IL_004f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0054: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0059: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_005e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_0063: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Target"" IL_0068: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__1.<>p__2"" IL_006d: ldloc.0 IL_006e: ldloc.1 IL_006f: ldloc.2 IL_0070: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0075: brtrue.s IL_00ad IL_0077: ldc.i4.0 IL_0078: ldc.i4.s 69 IL_007a: ldtoken ""C"" IL_007f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0084: ldc.i4.2 IL_0085: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_008a: dup IL_008b: ldc.i4.0 IL_008c: ldc.i4.0 IL_008d: ldnull IL_008e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0093: stelem.ref IL_0094: dup IL_0095: ldc.i4.1 IL_0096: ldc.i4.0 IL_0097: ldnull IL_0098: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_009d: stelem.ref IL_009e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00a3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00ad: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00b2: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00b7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_00bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_00c1: brtrue.s IL_0101 IL_00c3: ldc.i4.0 IL_00c4: ldtoken ""C"" IL_00c9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ce: ldc.i4.3 IL_00cf: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d4: dup IL_00d5: ldc.i4.0 IL_00d6: ldc.i4.0 IL_00d7: ldnull IL_00d8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00dd: stelem.ref IL_00de: dup IL_00df: ldc.i4.1 IL_00e0: ldc.i4.0 IL_00e1: ldnull IL_00e2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e7: stelem.ref IL_00e8: dup IL_00e9: ldc.i4.2 IL_00ea: ldc.i4.1 IL_00eb: ldnull IL_00ec: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00f1: stelem.ref IL_00f2: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f7: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00fc: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0101: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0106: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_010b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__1.<>p__0"" IL_0110: ldloc.0 IL_0111: ldloc.1 IL_0112: ldloc.2 IL_0113: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_0118: ldarg.3 IL_0119: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_011e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object)"" IL_0123: ret } "); #if TODO // locals and parameters shouldn't be spilled @"{ // Code size 288 (0x120) .maxstack 14 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: call ""int C.f()"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_000c: brtrue.s IL_005a IL_000e: ldc.i4 0x80 IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.4 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldnull IL_003b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0040: stelem.ref IL_0041: dup IL_0042: ldc.i4.3 IL_0043: ldc.i4.0 IL_0044: ldnull IL_0045: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_004a: stelem.ref IL_004b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0050: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0055: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_005f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>>.Target"" IL_0064: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>> C.<>o__0.<>p__2"" IL_0069: ldarg.1 IL_006a: ldarg.2 IL_006b: ldloc.0 IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_0071: brtrue.s IL_00a9 IL_0073: ldc.i4.0 IL_0074: ldc.i4.s 69 IL_0076: ldtoken ""C"" IL_007b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0080: ldc.i4.2 IL_0081: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0086: dup IL_0087: ldc.i4.0 IL_0088: ldc.i4.0 IL_0089: ldnull IL_008a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008f: stelem.ref IL_0090: dup IL_0091: ldc.i4.1 IL_0092: ldc.i4.0 IL_0093: ldnull IL_0094: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0099: stelem.ref IL_009a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_009f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00a4: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00a9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00ae: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00b3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__1"" IL_00b8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_00bd: brtrue.s IL_00fd IL_00bf: ldc.i4.0 IL_00c0: ldtoken ""C"" IL_00c5: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ca: ldc.i4.3 IL_00cb: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00d0: dup IL_00d1: ldc.i4.0 IL_00d2: ldc.i4.0 IL_00d3: ldnull IL_00d4: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d9: stelem.ref IL_00da: dup IL_00db: ldc.i4.1 IL_00dc: ldc.i4.0 IL_00dd: ldnull IL_00de: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00e3: stelem.ref IL_00e4: dup IL_00e5: ldc.i4.2 IL_00e6: ldc.i4.1 IL_00e7: ldnull IL_00e8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ed: stelem.ref IL_00ee: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00f3: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00f8: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_00fd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_0102: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>>.Target"" IL_0107: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>> C.<>o__0.<>p__0"" IL_010c: ldarg.1 IL_010d: ldarg.2 IL_010e: ldloc.0 IL_010f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int)"" IL_0114: ldarg.3 IL_0115: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_011a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object, int, object)"" IL_011f: ret } "); #endif } [Fact] public void CompoundStaticIndexerAssignment() { string source = @" public class C { public dynamic this[int a, object o] { get { return null; } set { } } public int f() { return 1; } public dynamic M(C c, dynamic v) { return c[f(), null] *= v; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 111 (0x6f) .maxstack 11 .locals init (C V_0, int V_1, object V_2) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: call ""int C.f()"" IL_0008: stloc.1 IL_0009: ldloc.0 IL_000a: ldloc.1 IL_000b: ldnull IL_000c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0011: brtrue.s IL_0049 IL_0013: ldc.i4.0 IL_0014: ldc.i4.s 69 IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: ldc.i4.2 IL_0021: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0026: dup IL_0027: ldc.i4.0 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.1 IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0039: stelem.ref IL_003a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0044: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_004e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__4.<>p__0"" IL_0058: ldloc.0 IL_0059: ldloc.1 IL_005a: ldnull IL_005b: callvirt ""dynamic C.this[int, object].get"" IL_0060: ldarg.2 IL_0061: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0066: dup IL_0067: stloc.2 IL_0068: callvirt ""void C.this[int, object].set"" IL_006d: ldloc.2 IL_006e: ret }"); #if TODO // locals and parameters shouldn't be spilled @" { // Code size 109 (0x6d) .maxstack 11 .locals init (int V_0, object V_1) IL_0000: ldarg.0 IL_0001: call ""int C.f()"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldloc.0 IL_0009: ldnull IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_000f: brtrue.s IL_0047 IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 69 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_0056: ldarg.1 IL_0057: ldloc.0 IL_0058: ldnull IL_0059: callvirt ""dynamic C.this[int, object].get"" IL_005e: ldarg.2 IL_005f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0064: dup IL_0065: stloc.1 IL_0066: callvirt ""void C.this[int, object].set"" IL_006b: ldloc.1 IL_006c: ret } "); #endif } [Fact] public void CompoundDynamicIndexerAssignment_ByRef() { string source = @" public class C { public dynamic Field; public C c; public C f() { return this; } public dynamic M(dynamic d, dynamic v) { int[] b = null; return d[ref f().Field, out b[10], c.c] *= v; } }"; // Dev11 emits different (unverifiable) code CompileAndVerifyIL(source, "C.M", @" { // Code size 342 (0x156) .maxstack 15 .locals init (object V_0, object& V_1, int& V_2, C V_3) IL_0000: ldnull IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: call ""C C.f()"" IL_0009: ldflda ""dynamic C.Field"" IL_000e: stloc.1 IL_000f: ldc.i4.s 10 IL_0011: ldelema ""int"" IL_0016: stloc.2 IL_0017: ldarg.0 IL_0018: ldfld ""C C.c"" IL_001d: ldfld ""C C.c"" IL_0022: stloc.3 IL_0023: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0028: brtrue.s IL_0082 IL_002a: ldc.i4 0x80 IL_002f: ldtoken ""C"" IL_0034: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0039: ldc.i4.5 IL_003a: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003f: dup IL_0040: ldc.i4.0 IL_0041: ldc.i4.0 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.s 9 IL_004d: ldnull IL_004e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0053: stelem.ref IL_0054: dup IL_0055: ldc.i4.2 IL_0056: ldc.i4.s 17 IL_0058: ldnull IL_0059: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005e: stelem.ref IL_005f: dup IL_0060: ldc.i4.3 IL_0061: ldc.i4.1 IL_0062: ldnull IL_0063: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0068: stelem.ref IL_0069: dup IL_006a: ldc.i4.4 IL_006b: ldc.i4.0 IL_006c: ldnull IL_006d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0072: stelem.ref IL_0073: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0078: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007d: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0082: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0087: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>>.Target"" IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>> C.<>o__3.<>p__2"" IL_0091: ldloc.0 IL_0092: ldloc.1 IL_0093: ldloc.2 IL_0094: ldloc.3 IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_009a: brtrue.s IL_00d2 IL_009c: ldc.i4.0 IL_009d: ldc.i4.s 69 IL_009f: ldtoken ""C"" IL_00a4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a9: ldc.i4.2 IL_00aa: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00af: dup IL_00b0: ldc.i4.0 IL_00b1: ldc.i4.0 IL_00b2: ldnull IL_00b3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b8: stelem.ref IL_00b9: dup IL_00ba: ldc.i4.1 IL_00bb: ldc.i4.0 IL_00bc: ldnull IL_00bd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c2: stelem.ref IL_00c3: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00cd: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00d2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00d7: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__3.<>p__1"" IL_00e1: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_00e6: brtrue.s IL_0132 IL_00e8: ldc.i4.0 IL_00e9: ldtoken ""C"" IL_00ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00f3: ldc.i4.4 IL_00f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00f9: dup IL_00fa: ldc.i4.0 IL_00fb: ldc.i4.0 IL_00fc: ldnull IL_00fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0102: stelem.ref IL_0103: dup IL_0104: ldc.i4.1 IL_0105: ldc.i4.s 9 IL_0107: ldnull IL_0108: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010d: stelem.ref IL_010e: dup IL_010f: ldc.i4.2 IL_0110: ldc.i4.s 17 IL_0112: ldnull IL_0113: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0118: stelem.ref IL_0119: dup IL_011a: ldc.i4.3 IL_011b: ldc.i4.1 IL_011c: ldnull IL_011d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0122: stelem.ref IL_0123: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0128: call ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_012d: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0132: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0137: ldfld ""<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object> System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>>.Target"" IL_013c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>> C.<>o__3.<>p__0"" IL_0141: ldloc.0 IL_0142: ldloc.1 IL_0143: ldloc.2 IL_0144: ldloc.3 IL_0145: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref int, C)"" IL_014a: ldarg.2 IL_014b: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_0150: callvirt ""object <>F{00000050}<System.Runtime.CompilerServices.CallSite, object, object, int, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, ref object, ref int, C, object)"" IL_0155: ret }"); } [Fact] public void CompoundDynamicArrayElementAccess() { string source = @" public class C { static dynamic[] d; static string s; static void M() { d[0] += s; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 99 (0x63) .maxstack 10 .locals init (object[] V_0) IL_0000: ldsfld ""dynamic[] C.d"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_000d: brtrue.s IL_0045 IL_000f: ldc.i4.0 IL_0010: ldc.i4.s 63 IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.0 IL_0025: ldnull IL_0026: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002b: stelem.ref IL_002c: dup IL_002d: ldc.i4.1 IL_002e: ldc.i4.1 IL_002f: ldnull IL_0030: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0035: stelem.ref IL_0036: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003b: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0040: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_0045: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_004a: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, string, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>>.Target"" IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>> C.<>o__2.<>p__0"" IL_0054: ldloc.0 IL_0055: ldc.i4.0 IL_0056: ldelem.ref IL_0057: ldsfld ""string C.s"" IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, string, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, string)"" IL_0061: stelem.ref IL_0062: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToStruct() { string source = @" class C { dynamic d = null; public void M() { bool ret = true; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 238 (0xee) .maxstack 13 .locals init (bool V_0) //ret IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_0007: brtrue.s IL_002e IL_0009: ldc.i4.s 16 IL_000b: ldtoken ""bool"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0024: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0029: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_002e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_0033: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__1.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_0042: brtrue.s IL_007a IL_0044: ldc.i4.0 IL_0045: ldc.i4.s 64 IL_0047: ldtoken ""C"" IL_004c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0051: ldc.i4.2 IL_0052: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0057: dup IL_0058: ldc.i4.0 IL_0059: ldc.i4.1 IL_005a: ldnull IL_005b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0060: stelem.ref IL_0061: dup IL_0062: ldc.i4.1 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__1.<>p__1"" IL_0089: ldloc.0 IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008f: brtrue.s IL_00c7 IL_0091: ldc.i4.0 IL_0092: ldc.i4.s 13 IL_0094: ldtoken ""C"" IL_0099: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009e: ldc.i4.2 IL_009f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a4: dup IL_00a5: ldc.i4.0 IL_00a6: ldc.i4.3 IL_00a7: ldnull IL_00a8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ad: stelem.ref IL_00ae: dup IL_00af: ldc.i4.1 IL_00b0: ldc.i4.0 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00c7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00cc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldc.i4.1 IL_00d7: ldarg.0 IL_00d8: ldfld ""dynamic C.d"" IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00e2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_00e7: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ec: stloc.0 IL_00ed: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToClass() { string source = @" class C { dynamic d = null; public void M() { C ret = null; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 238 (0xee) .maxstack 13 .locals init (C V_0) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_0007: brtrue.s IL_002e IL_0009: ldc.i4.s 16 IL_000b: ldtoken ""C"" IL_0010: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0015: ldtoken ""C"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0024: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0029: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_002e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_0033: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_0038: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_0042: brtrue.s IL_007a IL_0044: ldc.i4.0 IL_0045: ldc.i4.s 64 IL_0047: ldtoken ""C"" IL_004c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0051: ldc.i4.2 IL_0052: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0057: dup IL_0058: ldc.i4.0 IL_0059: ldc.i4.1 IL_005a: ldnull IL_005b: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0060: stelem.ref IL_0061: dup IL_0062: ldc.i4.1 IL_0063: ldc.i4.0 IL_0064: ldnull IL_0065: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006a: stelem.ref IL_006b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0070: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0075: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_007a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_007f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, C, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>>.Target"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>> C.<>o__1.<>p__1"" IL_0089: ldloc.0 IL_008a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008f: brtrue.s IL_00c7 IL_0091: ldc.i4.0 IL_0092: ldc.i4.s 13 IL_0094: ldtoken ""C"" IL_0099: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_009e: ldc.i4.2 IL_009f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00a4: dup IL_00a5: ldc.i4.0 IL_00a6: ldc.i4.3 IL_00a7: ldnull IL_00a8: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ad: stelem.ref IL_00ae: dup IL_00af: ldc.i4.1 IL_00b0: ldc.i4.0 IL_00b1: ldnull IL_00b2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00b7: stelem.ref IL_00b8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00bd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00c2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00c7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00cc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_00d1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_00d6: ldc.i4.1 IL_00d7: ldarg.0 IL_00d8: ldfld ""dynamic C.d"" IL_00dd: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00e2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, C, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_00e7: callvirt ""C System.Func<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00ec: stloc.0 IL_00ed: ret } "); } [Fact] public void CompoundAssignment_WithDynamicConversion_ToPointer() { string source = @" class C { dynamic d = null; public unsafe void M() { int* ret = null; ret &= (1 == d); } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,3): error CS0019: Operator '&=' cannot be applied to operands of type 'int*' and 'dynamic' Diagnostic(ErrorCode.ERR_BadBinaryOps, "ret &= (1 == d)").WithArguments("&=", "int*", "dynamic")); } [Fact] public void CompoundAssignment_WithNoDynamicConversion_Object() { string source = @" class C { dynamic d = null; public void M() { object ret = null; ret &= (1 == d); } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 174 (0xae) .maxstack 11 .locals init (object V_0) //ret IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0007: brtrue.s IL_003f IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 64 IL_000c: ldtoken ""C"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldc.i4.2 IL_0017: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001c: dup IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: ldnull IL_0020: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.1 IL_0028: ldc.i4.0 IL_0029: ldnull IL_002a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002f: stelem.ref IL_0030: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0035: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_003f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_0044: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_0049: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__1.<>p__1"" IL_004e: ldloc.0 IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_0054: brtrue.s IL_008c IL_0056: ldc.i4.0 IL_0057: ldc.i4.s 13 IL_0059: ldtoken ""C"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: ldc.i4.2 IL_0064: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0069: dup IL_006a: ldc.i4.0 IL_006b: ldc.i4.3 IL_006c: ldnull IL_006d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0072: stelem.ref IL_0073: dup IL_0074: ldc.i4.1 IL_0075: ldc.i4.0 IL_0076: ldnull IL_0077: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007c: stelem.ref IL_007d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0082: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0087: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_008c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_0091: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, int, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>>.Target"" IL_0096: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>> C.<>o__1.<>p__0"" IL_009b: ldc.i4.1 IL_009c: ldarg.0 IL_009d: ldfld ""dynamic C.d"" IL_00a2: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, int, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, int, object)"" IL_00a7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00ac: stloc.0 IL_00ad: ret } "); } [Fact] public void CompoundAssignment_UserDefinedOperator() { string source = @" class C { public static dynamic operator +(C lhs, int rhs) { return null; } static void M() { C c = new C(); c += 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 78 (0x4e) .maxstack 4 .locals init (C V_0) //c IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_000b: brtrue.s IL_0031 IL_000d: ldc.i4.0 IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0027: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0031: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0036: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, C> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>>.Target"" IL_003b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, C>> C.<>o__1.<>p__0"" IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: call ""dynamic C.op_Addition(C, int)"" IL_0047: callvirt ""C System.Func<System.Runtime.CompilerServices.CallSite, object, C>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_004c: stloc.0 IL_004d: ret } "); } [Fact] public void CompoundAssignment_Result() { string source = @" class C { bool a = true; bool b = true; dynamic d = null; int M() { if ((a &= d) != b) { return 1; } return 2; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 178 (0xb2) .maxstack 11 .locals init (bool V_0) IL_0000: ldarg.0 IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_0006: brtrue.s IL_002d IL_0008: ldc.i4.s 16 IL_000a: ldtoken ""bool"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0023: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0028: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_002d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_0032: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__3.<>p__1"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0041: brtrue.s IL_0079 IL_0043: ldc.i4.0 IL_0044: ldc.i4.s 64 IL_0046: ldtoken ""C"" IL_004b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0050: ldc.i4.2 IL_0051: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0056: dup IL_0057: ldc.i4.0 IL_0058: ldc.i4.1 IL_0059: ldnull IL_005a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_005f: stelem.ref IL_0060: dup IL_0061: ldc.i4.1 IL_0062: ldc.i4.0 IL_0063: ldnull IL_0064: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0069: stelem.ref IL_006a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_006f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0074: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0079: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_007e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>>.Target"" IL_0083: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>> C.<>o__3.<>p__0"" IL_0088: ldarg.0 IL_0089: ldfld ""bool C.a"" IL_008e: ldarg.0 IL_008f: ldfld ""dynamic C.d"" IL_0094: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, bool, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, bool, object)"" IL_0099: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_009e: dup IL_009f: stloc.0 IL_00a0: stfld ""bool C.a"" IL_00a5: ldloc.0 IL_00a6: ldarg.0 IL_00a7: ldfld ""bool C.b"" IL_00ac: beq.s IL_00b0 IL_00ae: ldc.i4.1 IL_00af: ret IL_00b0: ldc.i4.2 IL_00b1: ret }"); } [Fact] public void CompoundAssignment_Nullable() { string source = @" class C { int M() { bool? b = true; dynamic d = null; if ((d &= null) != (b &= null)) { return 1; } return 2; } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 278 (0x116) .maxstack 12 .locals init (bool? V_0, //b object V_1, //d bool? V_2, bool? V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""bool?..ctor(bool)"" IL_0008: ldnull IL_0009: stloc.1 IL_000a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_000f: brtrue.s IL_003d IL_0011: ldc.i4.0 IL_0012: ldc.i4.s 83 IL_0014: ldtoken ""C"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.1 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.UnaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0033: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0038: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_003d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_0042: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>o__0.<>p__2"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0051: brtrue.s IL_0089 IL_0053: ldc.i4.0 IL_0054: ldc.i4.s 35 IL_0056: ldtoken ""C"" IL_005b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0060: ldc.i4.2 IL_0061: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0066: dup IL_0067: ldc.i4.0 IL_0068: ldc.i4.0 IL_0069: ldnull IL_006a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006f: stelem.ref IL_0070: dup IL_0071: ldc.i4.1 IL_0072: ldc.i4.1 IL_0073: ldnull IL_0074: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0079: stelem.ref IL_007a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0084: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0089: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_008e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>>.Target"" IL_0093: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>> C.<>o__0.<>p__1"" IL_0098: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_009d: brtrue.s IL_00d5 IL_009f: ldc.i4.0 IL_00a0: ldc.i4.s 64 IL_00a2: ldtoken ""C"" IL_00a7: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ac: ldc.i4.2 IL_00ad: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00b2: dup IL_00b3: ldc.i4.0 IL_00b4: ldc.i4.0 IL_00b5: ldnull IL_00b6: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00bb: stelem.ref IL_00bc: dup IL_00bd: ldc.i4.1 IL_00be: ldc.i4.2 IL_00bf: ldnull IL_00c0: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c5: stelem.ref IL_00c6: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d0: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00da: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>>.Target"" IL_00df: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>> C.<>o__0.<>p__0"" IL_00e4: ldloc.1 IL_00e5: ldnull IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, object)"" IL_00eb: dup IL_00ec: stloc.1 IL_00ed: ldloc.0 IL_00ee: stloc.2 IL_00ef: ldloca.s V_2 IL_00f1: call ""bool bool?.GetValueOrDefault()"" IL_00f6: brtrue.s IL_00fb IL_00f8: ldloc.2 IL_00f9: br.s IL_0104 IL_00fb: ldloca.s V_3 IL_00fd: initobj ""bool?"" IL_0103: ldloc.3 IL_0104: dup IL_0105: stloc.0 IL_0106: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, bool?, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, bool?)"" IL_010b: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0110: brfalse.s IL_0114 IL_0112: ldc.i4.1 IL_0113: ret IL_0114: ldc.i4.2 IL_0115: ret } "); } [Fact] public void CompoundAssignment() { string source = @" class C { static void Main() { dynamic[] x = new string[] { ""hello"" }; x[0] += ""!""; System.Console.Write(x[0]); } } "; var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "hello!", references: new[] { ValueTupleRef, SystemRuntimeFacadeRef, CSharpRef, SystemCoreRef }); comp.VerifyDiagnostics(); // No runtime failure (System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.) // because of the special handling for dynamic in LocalRewriter.TransformCompoundAssignmentLHS } #endregion #region Object And Collection Initializers [Fact] public void DynamicObjectInitializer_Level2() { string source = @" using System; class C { public dynamic A { get; set; } static void M() { var x = new C { A = { B = 1 } }; } } "; // Bug in Dev11: it boxes the constant literal (1) and the corresponding call-site parameter is typed to object. CompileAndVerifyIL(source, "C.M", @" { // Code size 99 (0x63) .maxstack 8 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_0046 IL_000d: ldc.i4.0 IL_000e: ldstr ""B"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.2 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.3 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_004b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__0"" IL_0055: ldloc.0 IL_0056: callvirt ""dynamic C.A.get"" IL_005b: ldc.i4.1 IL_005c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0061: pop IL_0062: ret }"); } /// <summary> /// We can shared dynamic sites for GetMembers of level n-1 on level n for n >= 3. /// </summary> [Fact] public void DynamicObjectInitializer_Level3() { string source = @" using System; class C { public dynamic A { get; set; } static void M() { var x = new C { A = { B = { P = 1, Q = 2 } } }; } } "; // Dev11 creates 4 call sites: GetMember[B] #1, SetMember[P], GetMember[B] #2, SetMember[Q] and calls them as follows: // var c = new C(); // SetMember[P](GetMember[B](c) #1, 1) // SetMember[Q](GetMember[B](c) #2, 2) // // To maintain runtime compatibility we have to invoke GetMember[B] twice, but we can reuse the call-site: // We create 3 call sites: GetMember[B] #1, SetMember[P], SetMember[Q] // var c = new C(); // SetMember[P](GetMember[B](c) #1, 1) // SetMember[Q](GetMember[B](c) #1, 2) // // We initialize all sites up-front so that we are able to avoid duplication of call-site initialization. // // Also Dev11 emits flags (None, None) for SetMember[P], while Roslyn emits (None, UseCompileTimeType | Constant) since the RHS is a constant. CompileAndVerifyIL(source, "C.M", @" { // Code size 285 (0x11d) .maxstack 8 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_003c IL_000d: ldc.i4.0 IL_000e: ldstr ""B"" IL_0013: ldtoken ""C"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.1 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_0041: brtrue.s IL_007c IL_0043: ldc.i4.0 IL_0044: ldstr ""P"" IL_0049: ldtoken ""C"" IL_004e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0053: ldc.i4.2 IL_0054: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0059: dup IL_005a: ldc.i4.0 IL_005b: ldc.i4.0 IL_005c: ldnull IL_005d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0062: stelem.ref IL_0063: dup IL_0064: ldc.i4.1 IL_0065: ldc.i4.3 IL_0066: ldnull IL_0067: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_006c: stelem.ref IL_006d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0072: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0077: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_007c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_0081: brtrue.s IL_00bc IL_0083: ldc.i4.0 IL_0084: ldstr ""Q"" IL_0089: ldtoken ""C"" IL_008e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0093: ldc.i4.2 IL_0094: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0099: dup IL_009a: ldc.i4.0 IL_009b: ldc.i4.0 IL_009c: ldnull IL_009d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00a2: stelem.ref IL_00a3: dup IL_00a4: ldc.i4.1 IL_00a5: ldc.i4.3 IL_00a6: ldnull IL_00a7: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00ac: stelem.ref IL_00ad: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.SetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00b2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00b7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00bc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_00c1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00c6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__1"" IL_00cb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_00d0: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00d5: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_00da: ldloc.0 IL_00db: callvirt ""dynamic C.A.get"" IL_00e0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00e5: ldc.i4.1 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00eb: pop IL_00ec: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00f1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>>.Target"" IL_00f6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>> C.<>o__4.<>p__2"" IL_00fb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_0100: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0105: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__4.<>p__0"" IL_010a: ldloc.0 IL_010b: callvirt ""dynamic C.A.get"" IL_0110: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0115: ldc.i4.2 IL_0116: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, int, object>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_011b: pop IL_011c: ret } "); } [Fact] public void DynamicCollectionInitializer_DynamicReceiver_InStaticMethod() { string source = @" class C { public dynamic A { get; set; } static void M() { var x = new C { A = { { 1 } } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.3 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_005a: ldloc.0 IL_005b: callvirt ""dynamic C.A.get"" IL_0060: ldc.i4.1 IL_0061: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0066: ret } "); } [Fact] public void DynamicCollectionInitializer_DynamicReceiver_InInstanceMethod() { string source = @" class C { public dynamic A { get; set; } void M() { var x = new C { A = { { 1 } } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 103 (0x67) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.3 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__4.<>p__0"" IL_005a: ldloc.0 IL_005b: callvirt ""dynamic C.A.get"" IL_0060: ldc.i4.1 IL_0061: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_0066: ret } "); } [Fact] public void DynamicCollectionInitializer_StaticReceiver() { string source = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return null; } public void Add(int a) { } void M(dynamic d) { var x = new C { { d } }; } } "; CompileAndVerifyIL(source, "C.M", @" { // Code size 98 (0x62) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_000b: brtrue.s IL_004b IL_000d: ldc.i4 0x100 IL_0012: ldstr ""Add"" IL_0017: ldnull IL_0018: ldtoken ""C"" IL_001d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0022: ldc.i4.2 IL_0023: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0028: dup IL_0029: ldc.i4.0 IL_002a: ldc.i4.1 IL_002b: ldnull IL_002c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0031: stelem.ref IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_0050: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, C, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, C, object>> C.<>o__2.<>p__0"" IL_005a: ldloc.0 IL_005b: ldarg.1 IL_005c: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, C, object>.Invoke(System.Runtime.CompilerServices.CallSite, C, object)"" IL_0061: ret } "); } [Fact] public void ObjectAndCollectionInitializer() { string source = @" using System; using System.Collections.Generic; class Program { static void Main() { var c = new C { X = { Y = { 1 } } }; } } class C { public dynamic X = new X(); } class X { public List<int> Y; } "; CompileAndVerifyIL(source, "Program.Main", @" { // Code size 177 (0xb1) .maxstack 9 .locals init (C V_0) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_000b: brtrue.s IL_003c IL_000d: ldc.i4.0 IL_000e: ldstr ""Y"" IL_0013: ldtoken ""Program"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldc.i4.1 IL_001e: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0023: dup IL_0024: ldc.i4.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0032: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0037: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0041: brtrue.s IL_0081 IL_0043: ldc.i4 0x100 IL_0048: ldstr ""Add"" IL_004d: ldnull IL_004e: ldtoken ""Program"" IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0058: ldc.i4.2 IL_0059: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_005e: dup IL_005f: ldc.i4.0 IL_0060: ldc.i4.0 IL_0061: ldnull IL_0062: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.i4.3 IL_006b: ldnull IL_006c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0071: stelem.ref IL_0072: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0077: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0081: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0086: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, object, int>> Program.<>o__0.<>p__1"" IL_0090: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_0095: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_009a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> Program.<>o__0.<>p__0"" IL_009f: ldloc.0 IL_00a0: ldfld ""dynamic C.X"" IL_00a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00aa: ldc.i4.1 IL_00ab: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object, int)"" IL_00b0: ret } "); } #endregion #region Foreach [Fact] public void ForEach_StaticallyTypedVariable() { string source = @" class C { void M(dynamic d) { foreach (int x in d) { System.Console.WriteLine(x); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, System.IDisposable V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Collections.IEnumerable"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__0"" IL_003a: ldarg.1 IL_003b: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_0045: stloc.0 .try { IL_0046: br.s IL_0093 IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_004d: brtrue.s IL_0074 IL_004f: ldc.i4.s 16 IL_0051: ldtoken ""int"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldtoken ""C"" IL_0060: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0065: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_006a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_006f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0074: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0079: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>>.Target"" IL_007e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, int>> C.<>o__0.<>p__1"" IL_0083: ldloc.0 IL_0084: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0089: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, object, int>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_008e: call ""void System.Console.WriteLine(int)"" IL_0093: ldloc.0 IL_0094: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0099: brtrue.s IL_0048 IL_009b: leave.s IL_00ae } finally { IL_009d: ldloc.0 IL_009e: isinst ""System.IDisposable"" IL_00a3: stloc.1 IL_00a4: ldloc.1 IL_00a5: brfalse.s IL_00ad IL_00a7: ldloc.1 IL_00a8: callvirt ""void System.IDisposable.Dispose()"" IL_00ad: endfinally } IL_00ae: ret } "); } [Fact] public void ForEach_ImplicitlyTypedVariable() { string source = @" class C { void M(dynamic d) { foreach (var x in d) { System.Console.WriteLine(x); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 208 (0xd0) .maxstack 9 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.IDisposable V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken ""System.Collections.IEnumerable"" IL_000d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0021: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0026: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_002b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_0030: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>>.Target"" IL_0035: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>> C.<>o__0.<>p__1"" IL_003a: ldarg.1 IL_003b: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, object, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0040: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_0045: stloc.0 .try { IL_0046: br.s IL_00b4 IL_0048: ldloc.0 IL_0049: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_004e: stloc.1 IL_004f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0054: brtrue.s IL_0095 IL_0056: ldc.i4 0x100 IL_005b: ldstr ""WriteLine"" IL_0060: ldnull IL_0061: ldtoken ""C"" IL_0066: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006b: ldc.i4.2 IL_006c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0071: dup IL_0072: ldc.i4.0 IL_0073: ldc.i4.s 33 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.1 IL_007e: ldc.i4.0 IL_007f: ldnull IL_0080: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0085: stelem.ref IL_0086: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_008b: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0090: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_009a: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>>.Target"" IL_009f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>> C.<>o__0.<>p__0"" IL_00a4: ldtoken ""System.Console"" IL_00a9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00ae: ldloc.1 IL_00af: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, object>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, object)"" IL_00b4: ldloc.0 IL_00b5: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00ba: brtrue.s IL_0048 IL_00bc: leave.s IL_00cf } finally { IL_00be: ldloc.0 IL_00bf: isinst ""System.IDisposable"" IL_00c4: stloc.2 IL_00c5: ldloc.2 IL_00c6: brfalse.s IL_00ce IL_00c8: ldloc.2 IL_00c9: callvirt ""void System.IDisposable.Dispose()"" IL_00ce: endfinally } IL_00cf: ret }"); } [WorkItem(2720, "https://github.com/dotnet/roslyn/issues/2720")] [Fact] public void ContextTypeInAsyncLambda() { string source = @" using System; using System.Threading.Tasks; class C { static void Main() { dynamic d = Task.FromResult(""a""); G(async () => await d()); } static void G(Func<Task<object>> f) { } }"; CompileAndVerifyIL(source, "C.<>c__DisplayClass0_0.<<Main>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 537 (0x219) .maxstack 10 .locals init (int V_0, C.<>c__DisplayClass0_0 V_1, object V_2, object V_3, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4, System.Runtime.CompilerServices.INotifyCompletion V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_0.<<Main>b__0>d.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse IL_0185 IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__0"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_005f: brtrue.s IL_008b IL_0061: ldc.i4.0 IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.0 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>o__0.<>p__0"" IL_009a: ldloc.1 IL_009b: ldfld ""dynamic C.<>c__DisplayClass0_0.d"" IL_00a0: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00a5: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00aa: stloc.3 IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00b0: brtrue.s IL_00d7 IL_00b2: ldc.i4.s 16 IL_00b4: ldtoken ""bool"" IL_00b9: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00be: ldtoken ""C"" IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00cd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00dc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_00e1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__2"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_00eb: brtrue.s IL_011c IL_00ed: ldc.i4.0 IL_00ee: ldstr ""IsCompleted"" IL_00f3: ldtoken ""C"" IL_00f8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00fd: ldc.i4.1 IL_00fe: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0103: dup IL_0104: ldc.i4.0 IL_0105: ldc.i4.0 IL_0106: ldnull IL_0107: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010c: stelem.ref IL_010d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0112: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0117: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_011c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_0121: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0126: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__1"" IL_012b: ldloc.3 IL_012c: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0131: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0136: brtrue.s IL_019c IL_0138: ldarg.0 IL_0139: ldc.i4.0 IL_013a: dup IL_013b: stloc.0 IL_013c: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_0141: ldarg.0 IL_0142: ldloc.3 IL_0143: stfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_0148: ldloc.3 IL_0149: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_014e: stloc.s V_4 IL_0150: ldloc.s V_4 IL_0152: brtrue.s IL_016f IL_0154: ldloc.3 IL_0155: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015a: stloc.s V_5 IL_015c: ldarg.0 IL_015d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0162: ldloca.s V_5 IL_0164: ldarg.0 IL_0165: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<>c__DisplayClass0_0.<<Main>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<>c__DisplayClass0_0.<<Main>b__0>d)"" IL_016a: ldnull IL_016b: stloc.s V_5 IL_016d: br.s IL_017d IL_016f: ldarg.0 IL_0170: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0175: ldloca.s V_4 IL_0177: ldarg.0 IL_0178: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<>c__DisplayClass0_0.<<Main>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<>c__DisplayClass0_0.<<Main>b__0>d)"" IL_017d: ldnull IL_017e: stloc.s V_4 IL_0180: leave IL_0218 IL_0185: ldarg.0 IL_0186: ldfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_018b: stloc.3 IL_018c: ldarg.0 IL_018d: ldnull IL_018e: stfld ""object C.<>c__DisplayClass0_0.<<Main>b__0>d.<>u__1"" IL_0193: ldarg.0 IL_0194: ldc.i4.m1 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_019c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01a1: brtrue.s IL_01d3 IL_01a3: ldc.i4.0 IL_01a4: ldstr ""GetResult"" IL_01a9: ldnull IL_01aa: ldtoken ""C"" IL_01af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b4: ldc.i4.1 IL_01b5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ba: dup IL_01bb: ldc.i4.0 IL_01bc: ldc.i4.0 IL_01bd: ldnull IL_01be: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c3: stelem.ref IL_01c4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01ce: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01d8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>o.<>p__3"" IL_01e2: ldloc.3 IL_01e3: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01e8: stloc.2 IL_01e9: leave.s IL_0204 } catch System.Exception { IL_01eb: stloc.s V_6 IL_01ed: ldarg.0 IL_01ee: ldc.i4.s -2 IL_01f0: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_01f5: ldarg.0 IL_01f6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_01fb: ldloc.s V_6 IL_01fd: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0202: leave.s IL_0218 } IL_0204: ldarg.0 IL_0205: ldc.i4.s -2 IL_0207: stfld ""int C.<>c__DisplayClass0_0.<<Main>b__0>d.<>1__state"" IL_020c: ldarg.0 IL_020d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<>c__DisplayClass0_0.<<Main>b__0>d.<>t__builder"" IL_0212: ldloc.2 IL_0213: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_0218: ret }"); } [WorkItem(5323, "https://github.com/dotnet/roslyn/issues/5323")] [Fact] public void DynamicUsingWithYield1() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class Program { static void Main(string[] args) { foreach(var i in Iter()) { System.Console.WriteLine(i); } } static IEnumerable<Task> Iter() { dynamic d = 123; using (var t = D(d)) { yield return t; t.Wait(); } } static Task D(dynamic arg) { return Task.FromResult(1); } }"; var comp = CreateCompilationWithCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); } [WorkItem(5323, "https://github.com/dotnet/roslyn/issues/5323")] [Fact] public void DynamicUsingWithYield2() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class Program { static void Main(string[] args) { foreach(var i in Iter()) { System.Console.WriteLine(i); } } static IEnumerable<Task> Iter() { dynamic d = 123; var t = D(d); using (t) { yield return t; t.Wait(); } } static Task D(dynamic arg) { return Task.FromResult(1); } }"; var comp = CreateCompilationWithCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: @"System.Threading.Tasks.Task`1[System.Int32]"); } #endregion #region Using [Fact] public void UsingStatement() { string source = @" using System; class C { dynamic d = null; void M() { using (dynamic u = d) { Console.WriteLine(); } } }"; CompileAndVerifyIL(source, "C.M", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (object V_0, //u System.IDisposable V_1) IL_0000: ldarg.0 IL_0001: ldfld ""dynamic C.d"" IL_0006: stloc.0 IL_0007: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_000c: brtrue.s IL_0032 IL_000e: ldc.i4.0 IL_000f: ldtoken ""System.IDisposable"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: ldtoken ""C"" IL_001e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0023: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0028: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0032: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0037: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>>.Target"" IL_003c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>> C.<>o__1.<>p__0"" IL_0041: ldloc.0 IL_0042: callvirt ""System.IDisposable System.Func<System.Runtime.CompilerServices.CallSite, object, System.IDisposable>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0047: stloc.1 .try { IL_0048: call ""void System.Console.WriteLine()"" IL_004d: leave.s IL_0059 } finally { IL_004f: ldloc.1 IL_0050: brfalse.s IL_0058 IL_0052: ldloc.1 IL_0053: callvirt ""void System.IDisposable.Dispose()"" IL_0058: endfinally } IL_0059: ret } "); } #endregion #region Async [Fact] public void AwaitAwait() { string source = @" using System; using System.Threading.Tasks; class C { static dynamic d; static async void M() { var x = await await d; } }"; CompileAndVerifyIL(source, "C.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 855 (0x357) .maxstack 10 .locals init (int V_0, object V_1, object V_2, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_3, System.Runtime.CompilerServices.INotifyCompletion V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_013c IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: beq IL_02c4 IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__0"" IL_005a: ldsfld ""dynamic C.d"" IL_005f: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0064: stloc.2 IL_0065: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_006a: brtrue.s IL_0091 IL_006c: ldc.i4.s 16 IL_006e: ldtoken ""bool"" IL_0073: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0078: ldtoken ""C"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0087: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_0091: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_0096: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_009b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__2"" IL_00a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00a5: brtrue.s IL_00d6 IL_00a7: ldc.i4.0 IL_00a8: ldstr ""IsCompleted"" IL_00ad: ldtoken ""C"" IL_00b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b7: ldc.i4.1 IL_00b8: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00bd: dup IL_00be: ldc.i4.0 IL_00bf: ldc.i4.0 IL_00c0: ldnull IL_00c1: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00c6: stelem.ref IL_00c7: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00cc: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d1: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00d6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00db: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_00e0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__1"" IL_00e5: ldloc.2 IL_00e6: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00eb: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_00f0: brtrue.s IL_0153 IL_00f2: ldarg.0 IL_00f3: ldc.i4.0 IL_00f4: dup IL_00f5: stloc.0 IL_00f6: stfld ""int C.<M>d__1.<>1__state"" IL_00fb: ldarg.0 IL_00fc: ldloc.2 IL_00fd: stfld ""object C.<M>d__1.<>u__1"" IL_0102: ldloc.2 IL_0103: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0108: stloc.3 IL_0109: ldloc.3 IL_010a: brtrue.s IL_0127 IL_010c: ldloc.2 IL_010d: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_0112: stloc.s V_4 IL_0114: ldarg.0 IL_0115: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_011a: ldloca.s V_4 IL_011c: ldarg.0 IL_011d: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<M>d__1)"" IL_0122: ldnull IL_0123: stloc.s V_4 IL_0125: br.s IL_0135 IL_0127: ldarg.0 IL_0128: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_012d: ldloca.s V_3 IL_012f: ldarg.0 IL_0130: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<M>d__1)"" IL_0135: ldnull IL_0136: stloc.3 IL_0137: leave IL_0356 IL_013c: ldarg.0 IL_013d: ldfld ""object C.<M>d__1.<>u__1"" IL_0142: stloc.2 IL_0143: ldarg.0 IL_0144: ldnull IL_0145: stfld ""object C.<M>d__1.<>u__1"" IL_014a: ldarg.0 IL_014b: ldc.i4.m1 IL_014c: dup IL_014d: stloc.0 IL_014e: stfld ""int C.<M>d__1.<>1__state"" IL_0153: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_0158: brtrue.s IL_018a IL_015a: ldc.i4.0 IL_015b: ldstr ""GetResult"" IL_0160: ldnull IL_0161: ldtoken ""C"" IL_0166: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_016b: ldc.i4.1 IL_016c: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0171: dup IL_0172: ldc.i4.0 IL_0173: ldc.i4.0 IL_0174: ldnull IL_0175: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_017a: stelem.ref IL_017b: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0180: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0185: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_018a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_018f: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0194: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__3"" IL_0199: ldloc.2 IL_019a: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_019f: stloc.1 IL_01a0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01a5: brtrue.s IL_01d7 IL_01a7: ldc.i4.0 IL_01a8: ldstr ""GetAwaiter"" IL_01ad: ldnull IL_01ae: ldtoken ""C"" IL_01b3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b8: ldc.i4.1 IL_01b9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01be: dup IL_01bf: ldc.i4.0 IL_01c0: ldc.i4.0 IL_01c1: ldnull IL_01c2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c7: stelem.ref IL_01c8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01cd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01d2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01d7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01dc: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_01e1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__4"" IL_01e6: ldloc.1 IL_01e7: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_01ec: stloc.2 IL_01ed: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_01f2: brtrue.s IL_0219 IL_01f4: ldc.i4.s 16 IL_01f6: ldtoken ""bool"" IL_01fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0200: ldtoken ""C"" IL_0205: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_020a: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_020f: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0214: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_0219: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_021e: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>>.Target"" IL_0223: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, bool>> C.<M>d__1.<>o__1.<>p__6"" IL_0228: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_022d: brtrue.s IL_025e IL_022f: ldc.i4.0 IL_0230: ldstr ""IsCompleted"" IL_0235: ldtoken ""C"" IL_023a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_023f: ldc.i4.1 IL_0240: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0245: dup IL_0246: ldc.i4.0 IL_0247: ldc.i4.0 IL_0248: ldnull IL_0249: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_024e: stelem.ref IL_024f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0254: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0259: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_025e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_0263: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_0268: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__5"" IL_026d: ldloc.2 IL_026e: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0273: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, object, bool>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0278: brtrue.s IL_02db IL_027a: ldarg.0 IL_027b: ldc.i4.1 IL_027c: dup IL_027d: stloc.0 IL_027e: stfld ""int C.<M>d__1.<>1__state"" IL_0283: ldarg.0 IL_0284: ldloc.2 IL_0285: stfld ""object C.<M>d__1.<>u__1"" IL_028a: ldloc.2 IL_028b: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0290: stloc.3 IL_0291: ldloc.3 IL_0292: brtrue.s IL_02af IL_0294: ldloc.2 IL_0295: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_029a: stloc.s V_4 IL_029c: ldarg.0 IL_029d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_02a2: ldloca.s V_4 IL_02a4: ldarg.0 IL_02a5: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.INotifyCompletion, ref C.<M>d__1)"" IL_02aa: ldnull IL_02ab: stloc.s V_4 IL_02ad: br.s IL_02bd IL_02af: ldarg.0 IL_02b0: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_02b5: ldloca.s V_3 IL_02b7: ldarg.0 IL_02b8: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, C.<M>d__1>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref C.<M>d__1)"" IL_02bd: ldnull IL_02be: stloc.3 IL_02bf: leave IL_0356 IL_02c4: ldarg.0 IL_02c5: ldfld ""object C.<M>d__1.<>u__1"" IL_02ca: stloc.2 IL_02cb: ldarg.0 IL_02cc: ldnull IL_02cd: stfld ""object C.<M>d__1.<>u__1"" IL_02d2: ldarg.0 IL_02d3: ldc.i4.m1 IL_02d4: dup IL_02d5: stloc.0 IL_02d6: stfld ""int C.<M>d__1.<>1__state"" IL_02db: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_02e0: brtrue.s IL_0312 IL_02e2: ldc.i4.0 IL_02e3: ldstr ""GetResult"" IL_02e8: ldnull IL_02e9: ldtoken ""C"" IL_02ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_02f3: ldc.i4.1 IL_02f4: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_02f9: dup IL_02fa: ldc.i4.0 IL_02fb: ldc.i4.0 IL_02fc: ldnull IL_02fd: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0302: stelem.ref IL_0303: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0308: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_030d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0312: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0317: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, object, object> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>>.Target"" IL_031c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, object, object>> C.<M>d__1.<>o__1.<>p__7"" IL_0321: ldloc.2 IL_0322: callvirt ""object System.Func<System.Runtime.CompilerServices.CallSite, object, object>.Invoke(System.Runtime.CompilerServices.CallSite, object)"" IL_0327: pop IL_0328: leave.s IL_0343 } catch System.Exception { IL_032a: stloc.s V_5 IL_032c: ldarg.0 IL_032d: ldc.i4.s -2 IL_032f: stfld ""int C.<M>d__1.<>1__state"" IL_0334: ldarg.0 IL_0335: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_033a: ldloc.s V_5 IL_033c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0341: leave.s IL_0356 } IL_0343: ldarg.0 IL_0344: ldc.i4.s -2 IL_0346: stfld ""int C.<M>d__1.<>1__state"" IL_034b: ldarg.0 IL_034c: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.<M>d__1.<>t__builder"" IL_0351: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0356: ret } "); } [Fact] public void MissingCSharpArgumentInfoCreate() { string source = @"class C { static void F(dynamic d) { d.F(); } }"; var comp = CreateCompilationWithMscorlib45( new[] { DynamicAttributeSource, source }, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); comp.VerifyEmitDiagnostics( // (5,9): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // d.F(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(5, 9)); } [Fact] [WorkItem(377883, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377883")] public void MissingCSharpArgumentInfoCreate_Async() { string source = @"using System.Threading.Tasks; class C { static async Task F(dynamic d) { await d; } }"; var comp = CreateCompilationWithMscorlib45( new[] { DynamicAttributeSource, source }, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); comp.VerifyEmitDiagnostics( // (6,15): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // await d; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "d").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(6, 15)); } #endregion #region Regression Tests [ConditionalFact(typeof(DesktopOnly))] public void ByRefDynamic() { string source = @" public class Program { static void Main(string[] args) { System.Console.Write(Test1()); System.Console.Write("" ""); System.Console.Write(x.Length); } static dynamic x = new C1(); static int Test1() { return M1(ref x.Length); } static dynamic M1(ref dynamic d) { d = 321; return d; } } class C1 { public int Length = 123; } "; var comp = CompileAndVerify(source, expectedOutput: "321 123", references: new[] { CSharpRef }); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction1() { var source = @" using System; class Program { public static void Main() { M(""""); void M<T>(T slot) { slot = (dynamic)default; Console.WriteLine(slot is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__0_0`1'<T> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T>> '<>p__0' } // end of class <>o__0_0`1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::'<Main>g__M|0_0'<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<Main>g__M|0_0'<T> ( !!T slot ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2064 // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__0_0`1'<!!T>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>::Invoke(!0, !1) IL_0040: starg.s slot IL_0042: ldarg.0 IL_0043: box !!T IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<Main>g__M|0_0' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction2() { var source = @" using System; class Program { public static void Main() { M1<string, string>(""""); } public static void M1<T1, T2>(T1 a) { M2<T1, T2>(a); void M2<T3, T4>(T3 b) { M3<T3, T4>(b); void M3<T5, T6>(T5 c) { c = (dynamic)default; Console.WriteLine(c is null); } } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1_1`6'<T1, T2, T3, T4, T5, T6> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T5>> '<>p__0' } // end of class <>o__1_1`6 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::M1<string, string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig static void M1<T1, T2> ( !!T1 a ) cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M2|1_0'<!!T1, !!T2, !!T1, !!T2>(!!2) IL_0006: ret } // end of method Program::M1 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M1>g__M2|1_0'<T1, T2, T3, T4> ( !!T3 b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M3|1_1'<!!T1, !!T2, !!T3, !!T4, !!T3, !!T4>(!!4) IL_0006: ret } // end of method Program::'<M1>g__M2|1_0' .method assembly hidebysig static void '<M1>g__M3|1_1'<T1, T2, T3, T4, T5, T6> ( !!T5 c ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2074 // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T5 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !4>> class Program/'<>o__1_1`6'<!!T1, !!T2, !!T3, !!T4, !!T5, !!T6>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T5>::Invoke(!0, !1) IL_0040: starg.s c IL_0042: ldarg.0 IL_0043: box !!T5 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<M1>g__M3|1_1' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction3() { var source = @" using System; class Program { public static void Main() { M1(""""); } public static void M1<T1>(T1 a) { M2(a); void M2(T1 b) { b = (dynamic)default; Console.WriteLine(b is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1`1'<T1> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T1>> '<>p__0' } // end of class <>o__1`1 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::M1<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig static void M1<T1> ( !!T1 a ) cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<M1>g__M2|1_0'<!!T1>(!!0) IL_0006: ret } // end of method Program::M1 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<M1>g__M2|1_0'<T1> ( !!T1 b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T1 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !0>> class Program/'<>o__1`1'<!!T1>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T1>::Invoke(!0, !1) IL_0040: starg.s b IL_0042: ldarg.0 IL_0043: box !!T1 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<M1>g__M2|1_0' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction4() { var source = @" using System; class Program { public static void Main() { M1(""""); void M1<T>(T a) { M2(a); void M2<T>(T b) { b = (dynamic)default; Console.WriteLine(b is null); } } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Program", @" .class private auto ansi beforefieldinit Program extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__1_0`2'<T, T> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T>> '<>p__0' } // end of class <>o__1_0`2 // Methods .method public hidebysig static void Main () cil managed { // Method begins at RVA 0x2050 // Code size 11 (0xb) .maxstack 8 .entrypoint IL_0000: ldstr """" IL_0005: call void Program::'<Main>g__M1|0_0'<string>(!!0) IL_000a: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x205c // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Program::.ctor .method assembly hidebysig static void '<Main>g__M1|0_0'<T> ( !!T a ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call void Program::'<Main>g__M2|0_1'<!!T, !!T>(!!1) IL_0006: ret } // end of method Program::'<Main>g__M1|0_0' .method assembly hidebysig static void '<Main>g__M2|0_1'<T, T> ( !!T b ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken Program IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Program/'<>o__1_0`2'<!!T, !!T>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T>::Invoke(!0, !1) IL_0040: starg.s b IL_0042: ldarg.0 IL_0043: box !!T IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Program::'<Main>g__M2|0_1' } // end of class Program"); } [Fact] [WorkItem(41947, "https://github.com/dotnet/roslyn/issues/41947")] public void DynamicInGenericLocalFunction5() { var source = @" using System; class Program { public static void Main() { Class<int>.M(); } } class Class<T1> { public static void M() { M1(""""); void M1<T2>(T2 a) { a = (dynamic)default; Console.WriteLine(a is null); } } }"; VerifyTypeIL( CompileAndVerify(source, expectedOutput: "True", references: new[] { CSharpRef }), "Class`1", @" .class private auto ansi beforefieldinit Class`1<T1> extends [netstandard]System.Object { // Nested Types .class nested private auto ansi abstract sealed beforefieldinit '<>o__0_0`1'<T1, T2> extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public static class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !T2>> '<>p__0' } // end of class <>o__0_0`1 // Methods .method public hidebysig static void M () cil managed { // Method begins at RVA 0x205f // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr """" IL_0005: call void class Class`1<!T1>::'<M>g__M1|0_0'<string>(!!0) IL_000a: ret } // end of method Class`1::M .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2057 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Class`1::.ctor .method assembly hidebysig static void '<M>g__M1|0_0'<T2> ( !!T2 a ) cil managed { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x206c // Code size 81 (0x51) .maxstack 3 IL_0000: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_0005: brtrue.s IL_002b IL_0007: ldc.i4.0 IL_0008: ldtoken !!T2 IL_000d: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_0012: ldtoken class Class`1<!T1> IL_0017: call class [netstandard]System.Type [netstandard]System.Type::GetTypeFromHandle(valuetype [netstandard]System.RuntimeTypeHandle) IL_001c: call class [netstandard]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::Convert(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, class [netstandard]System.Type, class [netstandard]System.Type) IL_0021: call class [netstandard]System.Runtime.CompilerServices.CallSite`1<!0> class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>>::Create(class [netstandard]System.Runtime.CompilerServices.CallSiteBinder) IL_0026: stsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_002b: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_0030: ldfld !0 class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>>::Target IL_0035: ldsfld class [netstandard]System.Runtime.CompilerServices.CallSite`1<class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !1>> class Class`1/'<>o__0_0`1'<!T1, !!T2>::'<>p__0' IL_003a: ldnull IL_003b: callvirt instance !2 class [netstandard]System.Func`3<class [netstandard]System.Runtime.CompilerServices.CallSite, object, !!T2>::Invoke(!0, !1) IL_0040: starg.s a IL_0042: ldarg.0 IL_0043: box !!T2 IL_0048: ldnull IL_0049: ceq IL_004b: call void [netstandard]System.Console::WriteLine(bool) IL_0050: ret } // end of method Class`1::'<M>g__M1|0_0' } // end of class Class`1"); } private static void VerifyTypeIL(CompilationVerifier compilation, string typeName, string expected) { // .Net Core has different assemblies for the same standard library types as .Net Framework, meaning that that the emitted output will be different to the expected if we run them .Net Framework // Since we do not expect there to be any meaningful differences between output for .Net Core and .Net Framework, we will skip these tests on .Net Framework if (ExecutionConditionUtil.IsCoreClr) { compilation.VerifyTypeIL(typeName, expected); } } #endregion } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests { public class CSharp : AbstractMetadataAsSourceTests { [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void ExtractXMLFromDocComment() { var docCommentText = @"/// <summary> /// I am the very model of a modern major general. /// </summary>"; var expectedXMLFragment = @" <summary> I am the very model of a modern major general. </summary>"; var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); Assert.Equal(expectedXMLFragment, extractedXMLFragment); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestNativeInteger(bool allowDecompilation) { var metadataSource = "public class C { public nint i; public nuint i2; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public nint i; public nuint i2; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public nint i; public nuint i2; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInitOnlyProperty(bool allowDecompilation) { var metadataSource = @"public class C { public int Property { get; init; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } } "; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public int Property {{ get; init; }} }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public int Property {{ get; set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTupleWithNames(bool allowDecompilation) { var metadataSource = "public class C { public (int a, int b) t; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.CompilerServices; public class [|C|] {{ [TupleElementNames(new[] {{ ""a"", ""b"" }})] public (int a, int b) t; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public (int a, int b) t; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Load_from_0, "System.ValueTuple.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, WorkItem(26605, "https://github.com/dotnet/roslyn/issues/26605")] public async Task TestValueTuple(bool allowDecompilation) { using var context = TestContext.Create(LanguageNames.CSharp); var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll #endregion using System.Collections; namespace System {{ public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ public static ValueTuple Create(); public static ValueTuple<T1> Create<T1>(T1 item1); public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2); public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4); public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5); public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6); public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7); public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); public int CompareTo(ValueTuple other); public override bool Equals(object obj); public bool Equals(ValueTuple other); public override int GetHashCode(); public override string ToString(); }} }}", true => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Collections; using System.Runtime.InteropServices; namespace System {{ [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ int ITupleInternal.Size => 0; public override bool Equals(object obj) {{ return obj is ValueTuple; }} public bool Equals(ValueTuple other) {{ return true; }} bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {{ return other is ValueTuple; }} int IComparable.CompareTo(object other) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public int CompareTo(ValueTuple other) {{ return 0; }} int IStructuralComparable.CompareTo(object other, IComparer comparer) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public override int GetHashCode() {{ return 0; }} int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {{ return 0; }} int ITupleInternal.GetHashCode(IEqualityComparer comparer) {{ return 0; }} public override string ToString() {{ return ""()""; }} string ITupleInternal.ToStringEnd() {{ return "")""; }} public static ValueTuple Create() {{ return default(ValueTuple); }} public static ValueTuple<T1> Create<T1>(T1 item1) {{ return new ValueTuple<T1>(item1); }} public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2) {{ return (item1, item2); }} public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {{ return (item1, item2, item3); }} public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {{ return (item1, item2, item3, item4); }} public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {{ return (item1, item2, item3, item4, item5); }} public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {{ return (item1, item2, item3, item4, item5, item6); }} public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {{ return (item1, item2, item3, item4, item5, item6, item7); }} public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {{ return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); }} internal static int CombineHashCodes(int h1, int h2) {{ return ((h1 << 5) + h1) ^ h2; }} internal static int CombineHashCodes(int h1, int h2, int h3) {{ return CombineHashCodes(CombineHashCodes(h1, h2), h3); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {{ return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.WARN_Version_mismatch_Expected_0_Got_1, "4.0.0.0", "4.0.10.0")} {string.Format(CSharpEditorResources.Load_from_0, "System.Runtime.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.Core.v4_0_30319_17929.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} #endif", }; await context.GenerateAndVerifySourceAsync("System.ValueTuple", expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestExtendedPartialMethod1(bool allowDecompilation) { var metadataSource = "public partial class C { public partial void F(); public partial void F() { } }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public void F(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public void F() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests { public class CSharp : AbstractMetadataAsSourceTests { [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void ExtractXMLFromDocComment() { var docCommentText = @"/// <summary> /// I am the very model of a modern major general. /// </summary>"; var expectedXMLFragment = @" <summary> I am the very model of a modern major general. </summary>"; var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); Assert.Equal(expectedXMLFragment, extractedXMLFragment); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestNativeInteger(bool allowDecompilation) { var metadataSource = "public class C { public nint i; public nuint i2; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public nint i; public nuint i2; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public nint i; public nuint i2; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInitOnlyProperty(bool allowDecompilation) { var metadataSource = @"public class C { public int Property { get; init; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } } "; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public int Property {{ get; init; }} }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public int Property {{ get; set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTupleWithNames(bool allowDecompilation) { var metadataSource = "public class C { public (int a, int b) t; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.CompilerServices; public class [|C|] {{ [TupleElementNames(new[] {{ ""a"", ""b"" }})] public (int a, int b) t; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public (int a, int b) t; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Load_from_0, "System.ValueTuple.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, WorkItem(26605, "https://github.com/dotnet/roslyn/issues/26605")] public async Task TestValueTuple(bool allowDecompilation) { using var context = TestContext.Create(LanguageNames.CSharp); var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll #endregion using System.Collections; namespace System {{ public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ public static ValueTuple Create(); public static ValueTuple<T1> Create<T1>(T1 item1); public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2); public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4); public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5); public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6); public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7); public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); public int CompareTo(ValueTuple other); public override bool Equals(object obj); public bool Equals(ValueTuple other); public override int GetHashCode(); public override string ToString(); }} }}", true => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Collections; using System.Runtime.InteropServices; namespace System {{ [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ int ITupleInternal.Size => 0; public override bool Equals(object obj) {{ return obj is ValueTuple; }} public bool Equals(ValueTuple other) {{ return true; }} bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {{ return other is ValueTuple; }} int IComparable.CompareTo(object other) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public int CompareTo(ValueTuple other) {{ return 0; }} int IStructuralComparable.CompareTo(object other, IComparer comparer) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public override int GetHashCode() {{ return 0; }} int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {{ return 0; }} int ITupleInternal.GetHashCode(IEqualityComparer comparer) {{ return 0; }} public override string ToString() {{ return ""()""; }} string ITupleInternal.ToStringEnd() {{ return "")""; }} public static ValueTuple Create() {{ return default(ValueTuple); }} public static ValueTuple<T1> Create<T1>(T1 item1) {{ return new ValueTuple<T1>(item1); }} public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2) {{ return (item1, item2); }} public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {{ return (item1, item2, item3); }} public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {{ return (item1, item2, item3, item4); }} public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {{ return (item1, item2, item3, item4, item5); }} public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {{ return (item1, item2, item3, item4, item5, item6); }} public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {{ return (item1, item2, item3, item4, item5, item6, item7); }} public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {{ return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); }} internal static int CombineHashCodes(int h1, int h2) {{ return ((h1 << 5) + h1) ^ h2; }} internal static int CombineHashCodes(int h1, int h2, int h3) {{ return CombineHashCodes(CombineHashCodes(h1, h2), h3); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {{ return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.WARN_Version_mismatch_Expected_0_Got_1, "4.0.0.0", "4.0.10.0")} {string.Format(CSharpEditorResources.Load_from_0, "System.Runtime.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.Core.v4_0_30319_17929.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} #endif", }; await context.GenerateAndVerifySourceAsync("System.ValueTuple", expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestExtendedPartialMethod1(bool allowDecompilation) { var metadataSource = "public partial class C { public partial void F(); public partial void F() { } }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public void F(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public void F() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AddAnalyzerConfigDocumentUndoUnit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddAnalyzerConfigDocumentUndoUnit : AbstractAddDocumentUndoUnit { public AddAnalyzerConfigDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo, text) { } protected override Project AddDocument(Project fromProject) => fromProject.AddAnalyzerConfigDocument(DocumentInfo.Name, Text, DocumentInfo.Folders, DocumentInfo.FilePath).Project; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddAnalyzerConfigDocumentUndoUnit : AbstractAddDocumentUndoUnit { public AddAnalyzerConfigDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo, text) { } protected override Project AddDocument(Project fromProject) => fromProject.AddAnalyzerConfigDocument(DocumentInfo.Name, Text, DocumentInfo.Folders, DocumentInfo.FilePath).Project; } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./docs/features/GlobalUsingDirective.md
Global Using Directive ========================= The *Global Using Directive* feature extends using directive syntax with an optional `global` keyword that can precede the `using` keyword. The scope of Global Using Directives spans across all compilation units in the program. Proposal: https://github.com/dotnet/csharplang/blob/master/proposals/GlobalUsingDirective.md Feature branch: https://github.com/dotnet/roslyn/tree/features/GlobalUsingDirective Test plan: https://github.com/dotnet/roslyn/issues/51307
Global Using Directive ========================= The *Global Using Directive* feature extends using directive syntax with an optional `global` keyword that can precede the `using` keyword. The scope of Global Using Directives spans across all compilation units in the program. Proposal: https://github.com/dotnet/csharplang/blob/master/proposals/GlobalUsingDirective.md Feature branch: https://github.com/dotnet/roslyn/tree/features/GlobalUsingDirective Test plan: https://github.com/dotnet/roslyn/issues/51307
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/VisualBasic/Portable/Symbols/EmbeddedSymbols/EmbeddedSymbolManager.SymbolsCollection.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class EmbeddedSymbolManager Friend ReadOnly IsReferencedPredicate As Func(Of Symbol, Boolean) = Function(t) Not t.IsEmbedded OrElse Me.IsSymbolReferenced(t) Private ReadOnly _embedded As EmbeddedSymbolKind ''' <summary> Automatically embedded symbols (types, methods and fields) used in the current compilation </summary> Private ReadOnly _symbols As ConcurrentDictionary(Of Symbol, Boolean) ''' <summary> ''' Non-0 indicates that the collection of referenced symbols is sealed ''' and so no new symbols are supposed to be added. ''' </summary> Private _sealed As Integer = 0 ''' <summary> ''' True if StandardModuleAttribute was used in the current compilation ''' </summary> Private _standardModuleAttributeReferenced As Boolean = False Public Sub New(embedded As EmbeddedSymbolKind) ' Update assert if additional embedded kinds are expected. Debug.Assert((embedded And Not EmbeddedSymbolKind.All) = 0) _embedded = embedded If (embedded And EmbeddedSymbolKind.All) <> 0 Then ' If any bits are set, EmbeddedAttribute should be set. Debug.Assert((embedded And EmbeddedSymbolKind.EmbeddedAttribute) <> 0) _symbols = New ConcurrentDictionary(Of Symbol, Boolean)(ReferenceEqualityComparer.Instance) End If End Sub Public ReadOnly Property Embedded As EmbeddedSymbolKind Get Return _embedded End Get End Property ''' <summary> ''' Marks StandardModuleAttributeReference type as being references in the ''' current compilation. This method is to be used when a new type symbol for a ''' module is being created; we cannot pass the actual StandardModuleAttribute ''' type symbol because the symbol table is being constructed and calling ''' Compilation.GetWellKnownType(...) will cause infinite recursion. It does ''' not seem reasonable to special case this in symbol creation, so we just ''' mark StandardModuleAttribute attribute as referenced and then add ''' the actual symbol when MarkAllDeferredSymbols(...) is called. ''' </summary> Public Sub RegisterModuleDeclaration() If (_embedded And EmbeddedSymbolKind.VbCore) <> 0 Then _standardModuleAttributeReferenced = True End If End Sub #If DEBUG Then Private _markAllDeferredSymbolsAsReferencedIsCalled As Integer = ThreeState.Unknown #End If ''' <summary> ''' Mark all deferred types as referenced ''' </summary> Public Sub MarkAllDeferredSymbolsAsReferenced(compilation As VisualBasicCompilation) If Me._standardModuleAttributeReferenced Then MarkSymbolAsReferenced( compilation.GetWellKnownType( WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute)) End If #If DEBUG Then Interlocked.CompareExchange(_markAllDeferredSymbolsAsReferencedIsCalled, ThreeState.True, ThreeState.Unknown) #End If End Sub <Conditional("DEBUG")> Friend Sub AssertMarkAllDeferredSymbolsAsReferencedIsCalled() #If DEBUG Then Debug.Assert(Me._markAllDeferredSymbolsAsReferencedIsCalled = ThreeState.True) #End If End Sub ''' <summary> ''' Returns True if any embedded symbols are referenced. ''' ''' WARNING: the referenced symbols collection may not be sealed yet!!! ''' </summary> Public ReadOnly Property IsAnySymbolReferenced As Boolean Get Me.AssertMarkAllDeferredSymbolsAsReferencedIsCalled() Return (_symbols IsNot Nothing) AndAlso Not _symbols.IsEmpty End Get End Property ''' <summary> ''' Makes a snapshot of the current set of referenced symbols filtered by, ''' the set of symbols provided; may be called before the referenced symbol ''' collection is sealed. ''' </summary> Friend Sub GetCurrentReferencedSymbolsSnapshot(builder As ArrayBuilder(Of Symbol), filter As ConcurrentSet(Of Symbol)) Debug.Assert(builder IsNot Nothing) Debug.Assert(builder.Count = 0) Debug.Assert(filter IsNot Nothing) For Each pair In _symbols.ToArray() If Not filter.Contains(pair.Key) Then builder.Add(pair.Key) End If Next End Sub ''' <summary> ''' Checks if the embedded symbol provided is in the collection and adds it ''' into collection if not. ''' ''' See description of AddReferencedSymbolWithDependents for more details of how ''' it actually works. ''' </summary> Public Sub MarkSymbolAsReferenced(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) #If Not Debug Then ' In RELEASE don't add anything if the collection is sealed If _sealed <> 0 Then Return End If #End If Debug.Assert(symbol.IsDefinition) Debug.Assert(symbol.IsEmbedded) AddReferencedSymbolWithDependents(symbol, allSymbols) End Sub Public Sub MarkSymbolAsReferenced(symbol As Symbol) MarkSymbolAsReferenced(symbol, New ConcurrentSet(Of Symbol)(ReferenceEqualityComparer.Instance)) End Sub ''' <summary> ''' Returns True if the embedded symbol is known to be referenced in the current compilation. ''' </summary> Public Function IsSymbolReferenced(symbol As Symbol) As Boolean Debug.Assert(symbol.IsEmbedded) Me.AssertMarkAllDeferredSymbolsAsReferencedIsCalled() Return _symbols.TryGetValue(symbol, Nothing) End Function ''' <summary> ''' Seals the collection of referenced symbols, all *new* symbols passed ''' to SpawnSymbolCollection(...) will cause assert and be ignored. ''' </summary> Public Sub SealCollection() Interlocked.CompareExchange(_sealed, 1, 0) End Sub #Region "Add referenced symbol implementation" ''' <summary> ''' Checks if the embedded symbol provided is present in the 'allSymbols' and if not ''' adds it into 'allSymbols' as well as to the collection of referenced symbols ''' managed by this manager. Also adds all the 'dependent' symbols, i.e. symbols ''' which must also be marked as referenced if 'symbol' is referenced. ''' ''' NOTE that when a new embedded symbol is being added to the collection of referenced ''' symbols it should be added along with all the 'dependent' symbols. For example, if ''' we add a method symbol (T1.M1) we should ensure the containing type symbol (T1) is ''' added too, as well as its constructor (T1..ctor) and maybe attribute(s) (Attr1) set ''' on T1 and their constructors/fields (Attr1..ctor), etc... ''' ''' All dependent symbols must be added in the current thread not depending on ''' the other concurrent threads and avoiding possible race. Thus, let's suppose we have ''' the following dependencies: ''' ''' T1.M1 -> { T1, T1..ctor, Attr1, Attr1..ctor, ... } ''' ''' we cannot just check if T1.M1 exists in the collection of referenced symbols and not ''' add dependent symbols if it does; the reason is that T1.M1 may be added by a concurrent ''' thread, but its dependencies may not be added by that thread yet. So we need to ''' calculate all dependencies and try add all the symbols together. ''' ''' On the other hand it should be avoided that the method *always* goes through all ''' the dependencies for each symbol even though it may be definitely known that the symbol ''' is added in one of the previous operations by *the same thread*. To serve this purpose ''' the method uses 'allSymbols' collection to actually check whether or not the symbol ''' is added to the collection. This makes possible to reuse the same collection in several ''' consequent calls to AddReferencedSymbolWithDependents from the same thread; for example ''' in case one thread consequently adds lots of symbols, the thread may use the same ''' 'allSymbols' instance for efficient symbol filtering. ''' </summary> Private Sub AddReferencedSymbolWithDependents(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) If Not symbol.IsEmbedded Then Return End If Debug.Assert(symbol.IsDefinition) If allSymbols.Contains(symbol) Then Return ' was added in this thread before End If Select Case symbol.Kind Case SymbolKind.Field ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) Case SymbolKind.Method ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) ' if the method is an accessor Dim methKind As MethodKind = DirectCast(symbol, MethodSymbol).MethodKind Select Case methKind Case MethodKind.PropertyGet, MethodKind.PropertySet ' add associated property, note that adding any accessor will cause ' adding the property as well as the other accessor if any AddReferencedSymbolWithDependents(DirectCast(symbol, MethodSymbol).AssociatedSymbol, allSymbols) Case MethodKind.Ordinary, MethodKind.Constructor, MethodKind.SharedConstructor ' OK Case Else Throw ExceptionUtilities.UnexpectedValue(methKind) End Select Case SymbolKind.Property ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) ' add accessors Dim [property] = DirectCast(symbol, PropertySymbol) If [property].GetMethod IsNot Nothing Then AddReferencedSymbolWithDependents([property].GetMethod, allSymbols) End If If [property].SetMethod IsNot Nothing Then AddReferencedSymbolWithDependents([property].SetMethod, allSymbols) End If Case SymbolKind.NamedType ValidateType(DirectCast(symbol, NamedTypeSymbol)) ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add SOME type members For Each member In DirectCast(symbol, NamedTypeSymbol).GetMembers() Select Case member.Kind Case SymbolKind.Field ' Always add non-const fields If Not DirectCast(member, FieldSymbol).IsConst Then AddReferencedSymbolRaw(member, allSymbols) ' fields of embedded types are not supported Debug.Assert(Not DirectCast(member, FieldSymbol).Type.IsEmbedded) End If Case SymbolKind.Method Select Case DirectCast(member, MethodSymbol).MethodKind Case MethodKind.SharedConstructor, MethodKind.Constructor ' Add constructors AddReferencedSymbolRaw(member, allSymbols) End Select ' Don't add regular methods, all of them should be added on-demand ' All other method kinds should not get here, it is asserted in ValidateType(...) End Select Next If symbol.ContainingType IsNot Nothing Then AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) End If End Select End Sub Private Sub AddReferencedSymbolRaw(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) Debug.Assert(symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Property OrElse symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Field) If allSymbols.Add(symbol) Then If _sealed <> 0 Then ' Collection is sealed Debug.Assert(_symbols.ContainsKey(symbol)) Else _symbols.TryAdd(symbol, True) ' NOTE: there is still a chance that a new element is added to a sealed collection End If ' add symbol's attributes For Each attribute In symbol.GetAttributes() AddReferencedSymbolWithDependents(attribute.AttributeClass, allSymbols) Next End If End Sub #End Region <Conditional("DEBUG")> Private Shared Sub ValidateType(type As NamedTypeSymbol) Debug.Assert(type.TypeKind = TypeKind.Module OrElse type.TypeKind = TypeKind.Class AndAlso type.IsNotInheritable) For Each member In type.GetMembers() Select Case member.Kind Case SymbolKind.Field ValidateField(DirectCast(member, FieldSymbol)) Case SymbolKind.Method ValidateMethod(DirectCast(member, MethodSymbol)) Case SymbolKind.NamedType ' Nested types are OK Case SymbolKind.Property ' Properties are OK if the accessors are OK, and accessors will be ' checked separately since those will also appear in GetMembers(). Case Else ' No other symbol kinds are allowed Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End Sub <Conditional("DEBUG")> Private Shared Sub ValidateField(field As FieldSymbol) ' Fields are OK (initializers are checked in method compiler) Dim type = field.Type Debug.Assert(Not type.IsEmbedded OrElse type.IsTypeParameter) End Sub <Conditional("DEBUG")> Friend Shared Sub ValidateMethod(method As MethodSymbol) ' Constructors, regular methods, and property accessors are OK Dim kind = method.MethodKind Debug.Assert(kind = MethodKind.Constructor OrElse kind = MethodKind.SharedConstructor OrElse kind = MethodKind.Ordinary OrElse kind = MethodKind.PropertyGet OrElse kind = MethodKind.PropertySet) Debug.Assert(Not method.IsOverridable) Debug.Assert(method.ExplicitInterfaceImplementations.IsEmpty) Debug.Assert(Not method.ReturnType.IsEmbedded OrElse method.ReturnType.IsTypeParameter) Debug.Assert(method.GetReturnTypeAttributes().IsEmpty) For Each parameter In method.Parameters Debug.Assert(Not parameter.Type.IsEmbedded OrElse parameter.Type.IsTypeParameter) Debug.Assert(parameter.GetAttributes().IsEmpty) Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class EmbeddedSymbolManager Friend ReadOnly IsReferencedPredicate As Func(Of Symbol, Boolean) = Function(t) Not t.IsEmbedded OrElse Me.IsSymbolReferenced(t) Private ReadOnly _embedded As EmbeddedSymbolKind ''' <summary> Automatically embedded symbols (types, methods and fields) used in the current compilation </summary> Private ReadOnly _symbols As ConcurrentDictionary(Of Symbol, Boolean) ''' <summary> ''' Non-0 indicates that the collection of referenced symbols is sealed ''' and so no new symbols are supposed to be added. ''' </summary> Private _sealed As Integer = 0 ''' <summary> ''' True if StandardModuleAttribute was used in the current compilation ''' </summary> Private _standardModuleAttributeReferenced As Boolean = False Public Sub New(embedded As EmbeddedSymbolKind) ' Update assert if additional embedded kinds are expected. Debug.Assert((embedded And Not EmbeddedSymbolKind.All) = 0) _embedded = embedded If (embedded And EmbeddedSymbolKind.All) <> 0 Then ' If any bits are set, EmbeddedAttribute should be set. Debug.Assert((embedded And EmbeddedSymbolKind.EmbeddedAttribute) <> 0) _symbols = New ConcurrentDictionary(Of Symbol, Boolean)(ReferenceEqualityComparer.Instance) End If End Sub Public ReadOnly Property Embedded As EmbeddedSymbolKind Get Return _embedded End Get End Property ''' <summary> ''' Marks StandardModuleAttributeReference type as being references in the ''' current compilation. This method is to be used when a new type symbol for a ''' module is being created; we cannot pass the actual StandardModuleAttribute ''' type symbol because the symbol table is being constructed and calling ''' Compilation.GetWellKnownType(...) will cause infinite recursion. It does ''' not seem reasonable to special case this in symbol creation, so we just ''' mark StandardModuleAttribute attribute as referenced and then add ''' the actual symbol when MarkAllDeferredSymbols(...) is called. ''' </summary> Public Sub RegisterModuleDeclaration() If (_embedded And EmbeddedSymbolKind.VbCore) <> 0 Then _standardModuleAttributeReferenced = True End If End Sub #If DEBUG Then Private _markAllDeferredSymbolsAsReferencedIsCalled As Integer = ThreeState.Unknown #End If ''' <summary> ''' Mark all deferred types as referenced ''' </summary> Public Sub MarkAllDeferredSymbolsAsReferenced(compilation As VisualBasicCompilation) If Me._standardModuleAttributeReferenced Then MarkSymbolAsReferenced( compilation.GetWellKnownType( WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute)) End If #If DEBUG Then Interlocked.CompareExchange(_markAllDeferredSymbolsAsReferencedIsCalled, ThreeState.True, ThreeState.Unknown) #End If End Sub <Conditional("DEBUG")> Friend Sub AssertMarkAllDeferredSymbolsAsReferencedIsCalled() #If DEBUG Then Debug.Assert(Me._markAllDeferredSymbolsAsReferencedIsCalled = ThreeState.True) #End If End Sub ''' <summary> ''' Returns True if any embedded symbols are referenced. ''' ''' WARNING: the referenced symbols collection may not be sealed yet!!! ''' </summary> Public ReadOnly Property IsAnySymbolReferenced As Boolean Get Me.AssertMarkAllDeferredSymbolsAsReferencedIsCalled() Return (_symbols IsNot Nothing) AndAlso Not _symbols.IsEmpty End Get End Property ''' <summary> ''' Makes a snapshot of the current set of referenced symbols filtered by, ''' the set of symbols provided; may be called before the referenced symbol ''' collection is sealed. ''' </summary> Friend Sub GetCurrentReferencedSymbolsSnapshot(builder As ArrayBuilder(Of Symbol), filter As ConcurrentSet(Of Symbol)) Debug.Assert(builder IsNot Nothing) Debug.Assert(builder.Count = 0) Debug.Assert(filter IsNot Nothing) For Each pair In _symbols.ToArray() If Not filter.Contains(pair.Key) Then builder.Add(pair.Key) End If Next End Sub ''' <summary> ''' Checks if the embedded symbol provided is in the collection and adds it ''' into collection if not. ''' ''' See description of AddReferencedSymbolWithDependents for more details of how ''' it actually works. ''' </summary> Public Sub MarkSymbolAsReferenced(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) #If Not Debug Then ' In RELEASE don't add anything if the collection is sealed If _sealed <> 0 Then Return End If #End If Debug.Assert(symbol.IsDefinition) Debug.Assert(symbol.IsEmbedded) AddReferencedSymbolWithDependents(symbol, allSymbols) End Sub Public Sub MarkSymbolAsReferenced(symbol As Symbol) MarkSymbolAsReferenced(symbol, New ConcurrentSet(Of Symbol)(ReferenceEqualityComparer.Instance)) End Sub ''' <summary> ''' Returns True if the embedded symbol is known to be referenced in the current compilation. ''' </summary> Public Function IsSymbolReferenced(symbol As Symbol) As Boolean Debug.Assert(symbol.IsEmbedded) Me.AssertMarkAllDeferredSymbolsAsReferencedIsCalled() Return _symbols.TryGetValue(symbol, Nothing) End Function ''' <summary> ''' Seals the collection of referenced symbols, all *new* symbols passed ''' to SpawnSymbolCollection(...) will cause assert and be ignored. ''' </summary> Public Sub SealCollection() Interlocked.CompareExchange(_sealed, 1, 0) End Sub #Region "Add referenced symbol implementation" ''' <summary> ''' Checks if the embedded symbol provided is present in the 'allSymbols' and if not ''' adds it into 'allSymbols' as well as to the collection of referenced symbols ''' managed by this manager. Also adds all the 'dependent' symbols, i.e. symbols ''' which must also be marked as referenced if 'symbol' is referenced. ''' ''' NOTE that when a new embedded symbol is being added to the collection of referenced ''' symbols it should be added along with all the 'dependent' symbols. For example, if ''' we add a method symbol (T1.M1) we should ensure the containing type symbol (T1) is ''' added too, as well as its constructor (T1..ctor) and maybe attribute(s) (Attr1) set ''' on T1 and their constructors/fields (Attr1..ctor), etc... ''' ''' All dependent symbols must be added in the current thread not depending on ''' the other concurrent threads and avoiding possible race. Thus, let's suppose we have ''' the following dependencies: ''' ''' T1.M1 -> { T1, T1..ctor, Attr1, Attr1..ctor, ... } ''' ''' we cannot just check if T1.M1 exists in the collection of referenced symbols and not ''' add dependent symbols if it does; the reason is that T1.M1 may be added by a concurrent ''' thread, but its dependencies may not be added by that thread yet. So we need to ''' calculate all dependencies and try add all the symbols together. ''' ''' On the other hand it should be avoided that the method *always* goes through all ''' the dependencies for each symbol even though it may be definitely known that the symbol ''' is added in one of the previous operations by *the same thread*. To serve this purpose ''' the method uses 'allSymbols' collection to actually check whether or not the symbol ''' is added to the collection. This makes possible to reuse the same collection in several ''' consequent calls to AddReferencedSymbolWithDependents from the same thread; for example ''' in case one thread consequently adds lots of symbols, the thread may use the same ''' 'allSymbols' instance for efficient symbol filtering. ''' </summary> Private Sub AddReferencedSymbolWithDependents(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) If Not symbol.IsEmbedded Then Return End If Debug.Assert(symbol.IsDefinition) If allSymbols.Contains(symbol) Then Return ' was added in this thread before End If Select Case symbol.Kind Case SymbolKind.Field ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) Case SymbolKind.Method ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) ' if the method is an accessor Dim methKind As MethodKind = DirectCast(symbol, MethodSymbol).MethodKind Select Case methKind Case MethodKind.PropertyGet, MethodKind.PropertySet ' add associated property, note that adding any accessor will cause ' adding the property as well as the other accessor if any AddReferencedSymbolWithDependents(DirectCast(symbol, MethodSymbol).AssociatedSymbol, allSymbols) Case MethodKind.Ordinary, MethodKind.Constructor, MethodKind.SharedConstructor ' OK Case Else Throw ExceptionUtilities.UnexpectedValue(methKind) End Select Case SymbolKind.Property ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add the containing type AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) ' add accessors Dim [property] = DirectCast(symbol, PropertySymbol) If [property].GetMethod IsNot Nothing Then AddReferencedSymbolWithDependents([property].GetMethod, allSymbols) End If If [property].SetMethod IsNot Nothing Then AddReferencedSymbolWithDependents([property].SetMethod, allSymbols) End If Case SymbolKind.NamedType ValidateType(DirectCast(symbol, NamedTypeSymbol)) ' add the symbol itself AddReferencedSymbolRaw(symbol, allSymbols) ' add SOME type members For Each member In DirectCast(symbol, NamedTypeSymbol).GetMembers() Select Case member.Kind Case SymbolKind.Field ' Always add non-const fields If Not DirectCast(member, FieldSymbol).IsConst Then AddReferencedSymbolRaw(member, allSymbols) ' fields of embedded types are not supported Debug.Assert(Not DirectCast(member, FieldSymbol).Type.IsEmbedded) End If Case SymbolKind.Method Select Case DirectCast(member, MethodSymbol).MethodKind Case MethodKind.SharedConstructor, MethodKind.Constructor ' Add constructors AddReferencedSymbolRaw(member, allSymbols) End Select ' Don't add regular methods, all of them should be added on-demand ' All other method kinds should not get here, it is asserted in ValidateType(...) End Select Next If symbol.ContainingType IsNot Nothing Then AddReferencedSymbolWithDependents(symbol.ContainingType, allSymbols) End If End Select End Sub Private Sub AddReferencedSymbolRaw(symbol As Symbol, allSymbols As ConcurrentSet(Of Symbol)) Debug.Assert(symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Property OrElse symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Field) If allSymbols.Add(symbol) Then If _sealed <> 0 Then ' Collection is sealed Debug.Assert(_symbols.ContainsKey(symbol)) Else _symbols.TryAdd(symbol, True) ' NOTE: there is still a chance that a new element is added to a sealed collection End If ' add symbol's attributes For Each attribute In symbol.GetAttributes() AddReferencedSymbolWithDependents(attribute.AttributeClass, allSymbols) Next End If End Sub #End Region <Conditional("DEBUG")> Private Shared Sub ValidateType(type As NamedTypeSymbol) Debug.Assert(type.TypeKind = TypeKind.Module OrElse type.TypeKind = TypeKind.Class AndAlso type.IsNotInheritable) For Each member In type.GetMembers() Select Case member.Kind Case SymbolKind.Field ValidateField(DirectCast(member, FieldSymbol)) Case SymbolKind.Method ValidateMethod(DirectCast(member, MethodSymbol)) Case SymbolKind.NamedType ' Nested types are OK Case SymbolKind.Property ' Properties are OK if the accessors are OK, and accessors will be ' checked separately since those will also appear in GetMembers(). Case Else ' No other symbol kinds are allowed Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End Sub <Conditional("DEBUG")> Private Shared Sub ValidateField(field As FieldSymbol) ' Fields are OK (initializers are checked in method compiler) Dim type = field.Type Debug.Assert(Not type.IsEmbedded OrElse type.IsTypeParameter) End Sub <Conditional("DEBUG")> Friend Shared Sub ValidateMethod(method As MethodSymbol) ' Constructors, regular methods, and property accessors are OK Dim kind = method.MethodKind Debug.Assert(kind = MethodKind.Constructor OrElse kind = MethodKind.SharedConstructor OrElse kind = MethodKind.Ordinary OrElse kind = MethodKind.PropertyGet OrElse kind = MethodKind.PropertySet) Debug.Assert(Not method.IsOverridable) Debug.Assert(method.ExplicitInterfaceImplementations.IsEmpty) Debug.Assert(Not method.ReturnType.IsEmbedded OrElse method.ReturnType.IsTypeParameter) Debug.Assert(method.GetReturnTypeAttributes().IsEmpty) For Each parameter In method.Parameters Debug.Assert(Not parameter.Type.IsEmbedded OrElse parameter.Type.IsTypeParameter) Debug.Assert(parameter.GetAttributes().IsEmpty) Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Portable/Errors/DiagnosticInfoWithSymbols.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal class DiagnosticInfoWithSymbols : DiagnosticInfo { // not serialized: internal readonly ImmutableArray<Symbol> Symbols; internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, (int)errorCode, arguments) { this.Symbols = symbols; } internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments) { this.Symbols = 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. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal class DiagnosticInfoWithSymbols : DiagnosticInfo { // not serialized: internal readonly ImmutableArray<Symbol> Symbols; internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, (int)errorCode, arguments) { this.Symbols = symbols; } internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments) { this.Symbols = symbols; } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Test/Resources/Core/MetadataTests/Interop/IndexerWithByRefParam.il
// ilasm /dll IndexerWithByRefParam.il .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly IndexerWithByRefParam { } .class interface public abstract auto ansi import B { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 30 30 30 32 30 39 35 45 2D 30 30 30 30 2D 30 30 30 30 2D 43 30 30 30 2D 30 30 30 30 30 30 30 30 30 30 34 36 00 00 ) .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32& a) cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_Item(int32& a, int32 'value') cil managed { } .property instance int32 Item(int32&) { .get instance int32 B::get_Item(int32&) .set instance void B::set_Item(int32&, int32) } }
// ilasm /dll IndexerWithByRefParam.il .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly IndexerWithByRefParam { } .class interface public abstract auto ansi import B { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 30 30 30 32 30 39 35 45 2D 30 30 30 30 2D 30 30 30 30 2D 43 30 30 30 2D 30 30 30 30 30 30 30 30 30 30 34 36 00 00 ) .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) .method public hidebysig newslot specialname abstract virtual instance int32 get_Item(int32& a) cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_Item(int32& a, int32 'value') cil managed { } .property instance int32 Item(int32&) { .get instance int32 B::get_Item(int32&) .set instance void B::set_Item(int32&, int32) } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.Whitespace.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> protected class Whitespace : TriviaData { private readonly bool _elastic; public Whitespace(AnalyzerConfigOptions options, int space, bool elastic, string language) : this(options, lineBreaks: 0, indentation: space, elastic: elastic, language: language) { Contract.ThrowIfFalse(space >= 0); } public Whitespace(AnalyzerConfigOptions options, int lineBreaks, int indentation, bool elastic, string language) : base(options, language) { _elastic = elastic; // space and line breaks can be negative during formatting. but at the end, should be normalized // to >= 0 this.LineBreaks = lineBreaks; this.Spaces = indentation; } public override bool TreatAsElastic => _elastic; public override bool IsWhitespaceOnlyTrivia => true; public override bool ContainsChanges => false; public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { if (this.LineBreaks == 0 && this.Spaces == space) { return this; } return new ModifiedWhitespace(this.Options, this, /*lineBreak*/0, space, elastic: false, language: this.Language); } public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { Contract.ThrowIfFalse(line > 0); if (this.LineBreaks == line && this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, line, indentation, elastic: false, language: this.Language); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { if (this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, this.LineBreaks, indentation, elastic: false, language: this.Language); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { // nothing changed, nothing to format } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { /// <summary> /// represents a general trivia between two tokens. slightly more expensive than others since it /// needs to calculate stuff unlike other cases /// </summary> protected class Whitespace : TriviaData { private readonly bool _elastic; public Whitespace(AnalyzerConfigOptions options, int space, bool elastic, string language) : this(options, lineBreaks: 0, indentation: space, elastic: elastic, language: language) { Contract.ThrowIfFalse(space >= 0); } public Whitespace(AnalyzerConfigOptions options, int lineBreaks, int indentation, bool elastic, string language) : base(options, language) { _elastic = elastic; // space and line breaks can be negative during formatting. but at the end, should be normalized // to >= 0 this.LineBreaks = lineBreaks; this.Spaces = indentation; } public override bool TreatAsElastic => _elastic; public override bool IsWhitespaceOnlyTrivia => true; public override bool ContainsChanges => false; public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { if (this.LineBreaks == 0 && this.Spaces == space) { return this; } return new ModifiedWhitespace(this.Options, this, /*lineBreak*/0, space, elastic: false, language: this.Language); } public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { Contract.ThrowIfFalse(line > 0); if (this.LineBreaks == line && this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, line, indentation, elastic: false, language: this.Language); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { if (this.Spaces == indentation) { return this; } return new ModifiedWhitespace(this.Options, this, this.LineBreaks, indentation, elastic: false, language: this.Language); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { // nothing changed, nothing to format } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Scripting/CSharpTest/ScriptOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { public class ScriptOptionsTests : TestBase { [Fact] public void WithLanguageVersion() { var options = ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); Assert.Equal(LanguageVersion.CSharp8, ((CSharpParseOptions)options.ParseOptions).LanguageVersion); } [Fact] public void WithLanguageVersion_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); Assert.Same(options, options.WithLanguageVersion(LanguageVersion.CSharp8)); } [Fact] public void WithLanguageVersion_NonCSharpParseOptions_Throws() { var options = ScriptOptions.Default.WithParseOptions(new VisualBasicParseOptions(kind: SourceCodeKind.Script, languageVersion: VisualBasic.LanguageVersion.Latest)); Assert.Throws<InvalidOperationException>(() => options.WithLanguageVersion(LanguageVersion.CSharp8)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { public class ScriptOptionsTests : TestBase { [Fact] public void WithLanguageVersion() { var options = ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); Assert.Equal(LanguageVersion.CSharp8, ((CSharpParseOptions)options.ParseOptions).LanguageVersion); } [Fact] public void WithLanguageVersion_SameValueTwice_DoesNotCreateNewInstance() { var options = ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); Assert.Same(options, options.WithLanguageVersion(LanguageVersion.CSharp8)); } [Fact] public void WithLanguageVersion_NonCSharpParseOptions_Throws() { var options = ScriptOptions.Default.WithParseOptions(new VisualBasicParseOptions(kind: SourceCodeKind.Script, languageVersion: VisualBasic.LanguageVersion.Latest)); Assert.Throws<InvalidOperationException>(() => options.WithLanguageVersion(LanguageVersion.CSharp8)); } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceUserDefinedOperatorSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. private const TypeCompareKind ComparisonForUserDefinedOperators = TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; private readonly string _name; private readonly bool _isExpressionBodied; #nullable enable private readonly TypeSymbol? _explicitInterfaceType; #nullable disable protected SourceUserDefinedOperatorSymbolBase( MethodKind methodKind, TypeSymbol explicitInterfaceType, string name, SourceMemberContainerTypeSymbol containingType, Location location, CSharpSyntaxNode syntax, DeclarationModifiers declarationModifiers, bool hasBody, bool isExpressionBodied, bool isIterator, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { _explicitInterfaceType = explicitInterfaceType; _name = name; _isExpressionBodied = isExpressionBodied; this.CheckUnsafeModifier(declarationModifiers, diagnostics); // We will bind the formal parameters and the return type lazily. For now, // assume that the return type is non-void; when we do the lazy initialization // of the parameters and return type we will update the flag if necessary. this.MakeFlags(methodKind, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled); if (this.ContainingType.IsInterface && !IsAbstract && (methodKind == MethodKind.Conversion || name == WellKnownMemberNames.EqualityOperatorName || name == WellKnownMemberNames.InequalityOperatorName)) { // If we have an unsupported conversion or equality/inequality operator in an interface, we already have reported that fact as // an error. No need to cascade the error further. return; } if (this.ContainingType.IsStatic) { // Similarly if we're in a static class, though we have not reported it yet. // CS0715: '{0}': static classes cannot contain user-defined operators diagnostics.Add(ErrorCode.ERR_OperatorInStaticClass, location, this); return; } // SPEC: An operator declaration must include both a public and a // SPEC: static modifier if (this.IsExplicitInterfaceImplementation) { if (!this.IsStatic) { diagnostics.Add(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, this.Locations[0], this); } } else if (this.DeclaredAccessibility != Accessibility.Public || !this.IsStatic) { // CS0558: User-defined operator '...' must be declared static and public diagnostics.Add(ErrorCode.ERR_OperatorsMustBeStatic, this.Locations[0], this); } // SPEC: Because an external operator provides no actual implementation, // SPEC: its operator body consists of a semicolon. For expression-bodied // SPEC: operators, the body is an expression. For all other operators, // SPEC: the operator body consists of a block... if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (hasBody && (IsExtern || IsAbstract)) { Debug.Assert(!(IsAbstract && IsExtern)); if (IsExtern) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial) { // Do not report that the body is missing if the operator is marked as // partial or abstract; we will already have given an error for that so // there's no need to "cascade" the error. diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } // SPEC: It is an error for the same modifier to appear multiple times in an // SPEC: operator declaration. var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, location); } } protected static DeclarationModifiers MakeDeclarationModifiers(MethodKind methodKind, bool inInterface, BaseMethodDeclarationSyntax syntax, Location location, BindingDiagnosticBag diagnostics) { bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = inInterface && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; var allowedModifiers = DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Unsafe; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.AccessibilityMask; if (inInterface) { allowedModifiers |= DeclarationModifiers.Abstract; if (syntax is OperatorDeclarationSyntax { OperatorToken: var opToken } && opToken.Kind() is not (SyntaxKind.EqualsEqualsToken or SyntaxKind.ExclamationEqualsToken)) { allowedModifiers |= DeclarationModifiers.Sealed; } } } var result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( syntax.Modifiers, defaultAccess, allowedModifiers, location, diagnostics, modifierErrors: out _); if (inInterface) { if ((result & (DeclarationModifiers.Abstract | DeclarationModifiers.Sealed)) != 0) { if ((result & (DeclarationModifiers.Sealed | DeclarationModifiers.Abstract)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Abstract)) { diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Sealed)); result &= ~DeclarationModifiers.Sealed; } LanguageVersion availableVersion = ((CSharpParseOptions)location.SourceTree.Options).LanguageVersion; LanguageVersion requiredVersion = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); if (availableVersion < requiredVersion) { var requiredVersionArgument = new CSharpRequiredLanguageVersion(requiredVersion); var availableVersionArgument = availableVersion.ToDisplayString(); reportModifierIfPresent(result, DeclarationModifiers.Abstract, location, diagnostics, requiredVersionArgument, availableVersionArgument); reportModifierIfPresent(result, DeclarationModifiers.Sealed, location, diagnostics, requiredVersionArgument, availableVersionArgument); } result &= ~DeclarationModifiers.Sealed; } else if ((result & DeclarationModifiers.Static) != 0 && syntax is OperatorDeclarationSyntax { OperatorToken: var opToken } && opToken.Kind() is not (SyntaxKind.EqualsEqualsToken or SyntaxKind.ExclamationEqualsToken)) { Binder.CheckFeatureAvailability(location.SourceTree, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } } return result; static void reportModifierIfPresent(DeclarationModifiers result, DeclarationModifiers errorModifier, Location location, BindingDiagnosticBag diagnostics, CSharpRequiredLanguageVersion requiredVersionArgument, string availableVersionArgument) { if ((result & errorModifier) != 0) { diagnostics.Add(ErrorCode.ERR_InvalidModifierForLanguageVersion, location, ModifierUtils.ConvertSingleModifierToSyntaxText(errorModifier), availableVersionArgument, requiredVersionArgument); } } } protected (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindReturnType(BaseMethodDeclarationSyntax declarationSyntax, TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) { TypeWithAnnotations returnType; ImmutableArray<ParameterSymbol> parameters; var binder = this.DeclaringCompilation. GetBinderFactory(declarationSyntax.SyntaxTree).GetBinder(returnTypeSyntax, declarationSyntax, this); SyntaxToken arglistToken; var signatureBinder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks); parameters = ParameterHelpers.MakeParameters( signatureBinder, this, declarationSyntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: false, diagnostics: diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); // Regardless of whether __arglist appears in the source code, we do not mark // the operator method as being a varargs method. } returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // restricted types cannot be returned. // NOTE: Span-like types can be returned (if expression is returnable). if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } if (returnType.Type.IsStatic) { // Operators in interfaces was introduced in C# 8, so there's no need to be specially concerned about // maintaining backcompat with the native compiler bug around interfaces. // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), returnTypeSyntax.Location, returnType.Type); } return (returnType, parameters); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { var (returnType, parameters) = MakeParametersAndBindReturnType(diagnostics); MethodChecks(returnType, parameters, diagnostics); // If we have a static class then we already // have reported that fact as an error. No need to cascade the error further. if (this.ContainingType.IsStatic) { return; } CheckValueParameters(diagnostics); CheckOperatorSignatures(diagnostics); } protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { if (_explicitInterfaceType is object) { string interfaceMethodName; ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier; switch (syntaxReferenceOpt.GetSyntax()) { case OperatorDeclarationSyntax operatorDeclaration: interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(operatorDeclaration); explicitInterfaceSpecifier = operatorDeclaration.ExplicitInterfaceSpecifier; break; case ConversionOperatorDeclarationSyntax conversionDeclaration: interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(conversionDeclaration); explicitInterfaceSpecifier = conversionDeclaration.ExplicitInterfaceSpecifier; break; default: throw ExceptionUtilities.Unreachable; } return this.FindExplicitlyImplementedMethod(isOperator: true, _explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifier, diagnostics); } return null; } #nullable enable protected sealed override TypeSymbol? ExplicitInterfaceType => _explicitInterfaceType; #nullable disable private void CheckValueParameters(BindingDiagnosticBag diagnostics) { // SPEC: The parameters of an operator must be value parameters. foreach (var p in this.Parameters) { if (p.RefKind != RefKind.None && p.RefKind != RefKind.In) { diagnostics.Add(ErrorCode.ERR_IllegalRefParam, this.Locations[0]); break; } } } private void CheckOperatorSignatures(BindingDiagnosticBag diagnostics) { if (MethodKind == MethodKind.ExplicitInterfaceImplementation) { // The signature is driven by the interface return; } // Have we even got the right formal parameter arity? If not then // we are in an error recovery scenario and we should just bail // out immediately. if (!DoesOperatorHaveCorrectArity(this.Name, this.ParameterCount)) { return; } switch (this.Name) { case WellKnownMemberNames.ImplicitConversionName: case WellKnownMemberNames.ExplicitConversionName: CheckUserDefinedConversionSignature(diagnostics); break; case WellKnownMemberNames.UnaryNegationOperatorName: case WellKnownMemberNames.UnaryPlusOperatorName: case WellKnownMemberNames.LogicalNotOperatorName: case WellKnownMemberNames.OnesComplementOperatorName: CheckUnarySignature(diagnostics); break; case WellKnownMemberNames.TrueOperatorName: case WellKnownMemberNames.FalseOperatorName: CheckTrueFalseSignature(diagnostics); break; case WellKnownMemberNames.IncrementOperatorName: case WellKnownMemberNames.DecrementOperatorName: CheckIncrementDecrementSignature(diagnostics); break; case WellKnownMemberNames.LeftShiftOperatorName: case WellKnownMemberNames.RightShiftOperatorName: CheckShiftSignature(diagnostics); break; default: CheckBinarySignature(diagnostics); break; } } private static bool DoesOperatorHaveCorrectArity(string name, int parameterCount) { switch (name) { case WellKnownMemberNames.IncrementOperatorName: case WellKnownMemberNames.DecrementOperatorName: case WellKnownMemberNames.UnaryNegationOperatorName: case WellKnownMemberNames.UnaryPlusOperatorName: case WellKnownMemberNames.LogicalNotOperatorName: case WellKnownMemberNames.OnesComplementOperatorName: case WellKnownMemberNames.TrueOperatorName: case WellKnownMemberNames.FalseOperatorName: case WellKnownMemberNames.ImplicitConversionName: case WellKnownMemberNames.ExplicitConversionName: return parameterCount == 1; default: return parameterCount == 2; } } private void CheckUserDefinedConversionSignature(BindingDiagnosticBag diagnostics) { if (this.ReturnsVoid) { // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } // SPEC: For a given source type S and target type T, if S or T are // SPEC: nullable types let S0 and T0 refer to their underlying types, // SPEC: otherwise, S0 and T0 are equal to S and T, respectively. var source = this.GetParameterType(0); var target = this.ReturnType; var source0 = source.StrippedType(); var target0 = target.StrippedType(); // SPEC: A class or struct is permitted to declare a conversion from S to T // SPEC: only if all the following are true: // SPEC: Neither S0 nor T0 is an interface type. if (source0.IsInterfaceType() || target0.IsInterfaceType()) { // CS0552: '{0}': user-defined conversions to or from an interface are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithInterface, this.Locations[0], this); return; } // SPEC: Either S0 or T0 is the class or struct type in which the operator // SPEC: declaration takes place. if (!MatchesContainingType(source0) && !MatchesContainingType(target0) && // allow conversion between T and Nullable<T> in declaration of Nullable<T> !MatchesContainingType(source) && !MatchesContainingType(target)) { // CS0556: User-defined conversion must convert to or from the enclosing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_AbstractConversionNotInvolvingContainedType : ErrorCode.ERR_ConversionNotInvolvingContainedType, this.Locations[0]); return; } // SPEC: * S0 and T0 are different types: if ((ContainingType.SpecialType == SpecialType.System_Nullable_T) ? source.Equals(target, ComparisonForUserDefinedOperators) : source0.Equals(target0, ComparisonForUserDefinedOperators)) { // CS0555: User-defined operator cannot convert a type to itself diagnostics.Add(ErrorCode.ERR_IdentityConversion, this.Locations[0]); return; } // Those are the easy ones. Now we come to: // SPEC: // Excluding user-defined conversions, a conversion does not exist from // S to T or T to S. For the purposes of these rules, any type parameters // associated with S or T are considered to be unique types that have // no inheritance relationship with other types, and any constraints on // those type parameters are ignored. // A counter-intuitive consequence of this rule is that: // // class X<U> where U : X<U> // { // public implicit operator X<U>(U u) { return u; } // } // // is *legal*, even though there is *already* an implicit conversion // from U to X<U> because U is constrained to have such a conversion. // // In discussing the implications of this rule, let's call the // containing type (which may be a class or struct) "C". S and T // are the source and target types. // // If we have made it this far in the error analysis we already know that // exactly one of S and T is C or C? -- if two or zero were, then we'd // have already reported ERR_ConversionNotInvolvingContainedType or // ERR_IdentityConversion and returned. // // WOLOG for the purposes of this discussion let's assume that S is // the one that is C or C?, and that T is the one that is neither C nor C?. // // So the question is: under what circumstances could T-to-S or S-to-T, // be a valid conversion, by the definition of valid above? // // Let's consider what kinds of types T could be. T cannot be an interface // because we've already reported an error and returned if it is. If T is // a delegate, array, enum, pointer, struct or nullable type then there // is no built-in conversion from T to the user-declared class/struct // C, or to C?. If T is a type parameter, then by assumption the type // parameter has no constraints, and therefore is not convertible to // C or C?. // // That leaves T to be a class. We already know that T is not C, (or C?, // since T is a class) and therefore there is no identity conversion from T to S. // // Suppose S is C and C is a class. Then the only way that there can be a // conversion between T and S is if T is a base class of S or S is a base class of T. // // Suppose S is C and C is a struct. Then the only way that there can be a // conversion between T and S is if T is a base class of S. (And T would // have to be System.Object or System.ValueType.) // // Suppose S is C? and C is a struct. Then the only way that there can be a // conversion between T and S is again, if T is a base class of S. // // Summing up: // // WOLOG, we assume that T is not C or C?, and S is C or C?. The conversion is // illegal only if T is a class, and either T is a base class of S, or S is a // base class of T. if (source.IsDynamic() || target.IsDynamic()) { // '{0}': user-defined conversions to or from the dynamic type are not allowed diagnostics.Add(ErrorCode.ERR_BadDynamicConversion, this.Locations[0], this); return; } TypeSymbol same; TypeSymbol different; if (MatchesContainingType(source0)) { same = source; different = target; } else { same = target; different = source; } if (different.IsClassType() && !same.IsTypeParameter()) { // different is a class type: Debug.Assert(!different.IsTypeParameter()); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (same.IsDerivedFrom(different, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)) { // '{0}': user-defined conversions to or from a base type are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithBase, this.Locations[0], this); } else if (different.IsDerivedFrom(same, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)) { // '{0}': user-defined conversions to or from a derived type are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithDerived, this.Locations[0], this); } diagnostics.Add(this.Locations[0], useSiteInfo); } } private void CheckUnarySignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary + - ! ~ operator must take a single parameter of type // SPEC: T or T? and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) { // The parameter of a unary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The Roslyn parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } private void CheckTrueFalseSignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary true or false operator must take a single parameter of type // SPEC: T or T? and must return type bool. if (this.ReturnType.SpecialType != SpecialType.System_Boolean) { // The return type of operator True or False must be bool diagnostics.Add(ErrorCode.ERR_OpTFRetType, this.Locations[0]); } if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) { // The parameter of a unary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); } } private void CheckIncrementDecrementSignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary ++ or -- operator must take a single parameter of type T or T? // SPEC: and it must return that same type or a type derived from it. // The native compiler error reporting behavior is not very good in some cases // here, both because it reports the wrong errors, and because the wording // of the error messages is misleading. The native compiler reports two errors: // CS0448: The return type for ++ or -- operator must be the // containing type or derived from the containing type // // CS0559: The parameter type for ++ or -- operator must be the containing type // // Neither error message mentions nullable types. But worse, there is a // situation in which the native compiler reports a misleading error: // // struct S { public static S operator ++(S? s) { ... } } // // This reports CS0559, but that is not the error; the *parameter* is perfectly // legal. The error is that the return type does not match the parameter type. // // I have changed the error message to reflect the true error, and we now // report 0448, not 0559, in the given scenario. The error is now: // // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type // // However, this now means that we must make *another* change from native compiler // behavior. The native compiler would report both 0448 and 0559 when given: // // struct S { public static int operator ++(int s) { ... } } // // The previous wording of error 0448 was *correct* in this scenario, but not // it is wrong because it *does* match the formal parameter type. // // The solution is: First see if 0559 must be reported. Only if the formal // parameter type is *good* do we then go on to try to report an error against // the return type. var parameterType = this.GetParameterType(0); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!MatchesContainingType(parameterType.StrippedType())) { // CS0559: The parameter type for ++ or -- operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractIncDecSignature : ErrorCode.ERR_BadIncDecSignature, this.Locations[0]); } else if (!(parameterType.IsTypeParameter() ? this.ReturnType.Equals(parameterType, ComparisonForUserDefinedOperators) : ((IsAbstract && IsContainingType(parameterType) && IsSelfConstrainedTypeParameter(this.ReturnType)) || this.ReturnType.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)))) { // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractIncDecRetType : ErrorCode.ERR_BadIncDecRetType, this.Locations[0]); } diagnostics.Add(this.Locations[0], useSiteInfo); } private bool MatchesContainingType(TypeSymbol type) { return IsContainingType(type) || (IsAbstract && IsSelfConstrainedTypeParameter(type)); } private bool IsContainingType(TypeSymbol type) { return type.Equals(this.ContainingType, ComparisonForUserDefinedOperators); } public static bool IsSelfConstrainedTypeParameter(TypeSymbol type, NamedTypeSymbol containingType) { Debug.Assert(containingType.IsDefinition); return type is TypeParameterSymbol p && // https://github.com/dotnet/roslyn/issues/53801: For now assuming the type parameter must belong to the containing type. (object)p.ContainingSymbol == containingType && // https://github.com/dotnet/roslyn/issues/53801: For now assume containing type must be one of the directly specified constraints. p.ConstraintTypesNoUseSiteDiagnostics.Any((typeArgument, containingType) => typeArgument.Type.Equals(containingType, ComparisonForUserDefinedOperators), containingType); } private bool IsSelfConstrainedTypeParameter(TypeSymbol type) { return IsSelfConstrainedTypeParameter(type, this.ContainingType); } private void CheckShiftSignature(BindingDiagnosticBag diagnostics) { // SPEC: A binary << or >> operator must take two parameters, the first // SPEC: of which must have type T or T? and the second of which must // SPEC: have type int or int?, and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType()) || this.GetParameterType(1).StrippedType().SpecialType != SpecialType.System_Int32) { // CS0546: The first operand of an overloaded shift operator must have the // same type as the containing type, and the type of the second // operand must be int diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadShiftOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The Roslyn parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } private void CheckBinarySignature(BindingDiagnosticBag diagnostics) { // SPEC: A binary nonshift operator must take two parameters, at least // SPEC: one of which must have the type T or T?, and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType()) && !MatchesContainingType(this.GetParameterType(1).StrippedType())) { // CS0563: One of the parameters of a binary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractBinaryOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } public sealed override string Name { get { return _name; } } public sealed override bool IsVararg { get { return false; } } public sealed override bool IsExtensionMethod { get { return false; } } public sealed override ImmutableArray<Location> Locations { get { return this.locations; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override RefKind RefKind { get { return RefKind.None; } } internal sealed override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { NameSyntax name; switch (syntaxReferenceOpt.GetSyntax()) { case OperatorDeclarationSyntax operatorDeclaration: Debug.Assert(operatorDeclaration.ExplicitInterfaceSpecifier != null); name = operatorDeclaration.ExplicitInterfaceSpecifier.Name; break; case ConversionOperatorDeclarationSyntax conversionDeclaration: Debug.Assert(conversionDeclaration.ExplicitInterfaceSpecifier != null); name = conversionDeclaration.ExplicitInterfaceSpecifier.Name; break; default: throw ExceptionUtilities.Unreachable; } _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(name), diagnostics); } } protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceUserDefinedOperatorSymbolBase : SourceOrdinaryMethodOrUserDefinedOperatorSymbol { // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. private const TypeCompareKind ComparisonForUserDefinedOperators = TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; private readonly string _name; private readonly bool _isExpressionBodied; #nullable enable private readonly TypeSymbol? _explicitInterfaceType; #nullable disable protected SourceUserDefinedOperatorSymbolBase( MethodKind methodKind, TypeSymbol explicitInterfaceType, string name, SourceMemberContainerTypeSymbol containingType, Location location, CSharpSyntaxNode syntax, DeclarationModifiers declarationModifiers, bool hasBody, bool isExpressionBodied, bool isIterator, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), location, isIterator: isIterator) { _explicitInterfaceType = explicitInterfaceType; _name = name; _isExpressionBodied = isExpressionBodied; this.CheckUnsafeModifier(declarationModifiers, diagnostics); // We will bind the formal parameters and the return type lazily. For now, // assume that the return type is non-void; when we do the lazy initialization // of the parameters and return type we will update the flag if necessary. this.MakeFlags(methodKind, declarationModifiers, returnsVoid: false, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled); if (this.ContainingType.IsInterface && !IsAbstract && (methodKind == MethodKind.Conversion || name == WellKnownMemberNames.EqualityOperatorName || name == WellKnownMemberNames.InequalityOperatorName)) { // If we have an unsupported conversion or equality/inequality operator in an interface, we already have reported that fact as // an error. No need to cascade the error further. return; } if (this.ContainingType.IsStatic) { // Similarly if we're in a static class, though we have not reported it yet. // CS0715: '{0}': static classes cannot contain user-defined operators diagnostics.Add(ErrorCode.ERR_OperatorInStaticClass, location, this); return; } // SPEC: An operator declaration must include both a public and a // SPEC: static modifier if (this.IsExplicitInterfaceImplementation) { if (!this.IsStatic) { diagnostics.Add(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, this.Locations[0], this); } } else if (this.DeclaredAccessibility != Accessibility.Public || !this.IsStatic) { // CS0558: User-defined operator '...' must be declared static and public diagnostics.Add(ErrorCode.ERR_OperatorsMustBeStatic, this.Locations[0], this); } // SPEC: Because an external operator provides no actual implementation, // SPEC: its operator body consists of a semicolon. For expression-bodied // SPEC: operators, the body is an expression. For all other operators, // SPEC: the operator body consists of a block... if (IsAbstract && IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this); } else if (hasBody && (IsExtern || IsAbstract)) { Debug.Assert(!(IsAbstract && IsExtern)); if (IsExtern) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } } else if (!hasBody && !IsExtern && !IsAbstract && !IsPartial) { // Do not report that the body is missing if the operator is marked as // partial or abstract; we will already have given an error for that so // there's no need to "cascade" the error. diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } // SPEC: It is an error for the same modifier to appear multiple times in an // SPEC: operator declaration. var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, location); } } protected static DeclarationModifiers MakeDeclarationModifiers(MethodKind methodKind, bool inInterface, BaseMethodDeclarationSyntax syntax, Location location, BindingDiagnosticBag diagnostics) { bool isExplicitInterfaceImplementation = methodKind == MethodKind.ExplicitInterfaceImplementation; var defaultAccess = inInterface && !isExplicitInterfaceImplementation ? DeclarationModifiers.Public : DeclarationModifiers.Private; var allowedModifiers = DeclarationModifiers.Static | DeclarationModifiers.Extern | DeclarationModifiers.Unsafe; if (!isExplicitInterfaceImplementation) { allowedModifiers |= DeclarationModifiers.AccessibilityMask; if (inInterface) { allowedModifiers |= DeclarationModifiers.Abstract; if (syntax is OperatorDeclarationSyntax { OperatorToken: var opToken } && opToken.Kind() is not (SyntaxKind.EqualsEqualsToken or SyntaxKind.ExclamationEqualsToken)) { allowedModifiers |= DeclarationModifiers.Sealed; } } } var result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( syntax.Modifiers, defaultAccess, allowedModifiers, location, diagnostics, modifierErrors: out _); if (inInterface) { if ((result & (DeclarationModifiers.Abstract | DeclarationModifiers.Sealed)) != 0) { if ((result & (DeclarationModifiers.Sealed | DeclarationModifiers.Abstract)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Abstract)) { diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, ModifierUtils.ConvertSingleModifierToSyntaxText(DeclarationModifiers.Sealed)); result &= ~DeclarationModifiers.Sealed; } LanguageVersion availableVersion = ((CSharpParseOptions)location.SourceTree.Options).LanguageVersion; LanguageVersion requiredVersion = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion(); if (availableVersion < requiredVersion) { var requiredVersionArgument = new CSharpRequiredLanguageVersion(requiredVersion); var availableVersionArgument = availableVersion.ToDisplayString(); reportModifierIfPresent(result, DeclarationModifiers.Abstract, location, diagnostics, requiredVersionArgument, availableVersionArgument); reportModifierIfPresent(result, DeclarationModifiers.Sealed, location, diagnostics, requiredVersionArgument, availableVersionArgument); } result &= ~DeclarationModifiers.Sealed; } else if ((result & DeclarationModifiers.Static) != 0 && syntax is OperatorDeclarationSyntax { OperatorToken: var opToken } && opToken.Kind() is not (SyntaxKind.EqualsEqualsToken or SyntaxKind.ExclamationEqualsToken)) { Binder.CheckFeatureAvailability(location.SourceTree, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } } return result; static void reportModifierIfPresent(DeclarationModifiers result, DeclarationModifiers errorModifier, Location location, BindingDiagnosticBag diagnostics, CSharpRequiredLanguageVersion requiredVersionArgument, string availableVersionArgument) { if ((result & errorModifier) != 0) { diagnostics.Add(ErrorCode.ERR_InvalidModifierForLanguageVersion, location, ModifierUtils.ConvertSingleModifierToSyntaxText(errorModifier), availableVersionArgument, requiredVersionArgument); } } } protected (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindReturnType(BaseMethodDeclarationSyntax declarationSyntax, TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) { TypeWithAnnotations returnType; ImmutableArray<ParameterSymbol> parameters; var binder = this.DeclaringCompilation. GetBinderFactory(declarationSyntax.SyntaxTree).GetBinder(returnTypeSyntax, declarationSyntax, this); SyntaxToken arglistToken; var signatureBinder = binder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks); parameters = ParameterHelpers.MakeParameters( signatureBinder, this, declarationSyntax.ParameterList, out arglistToken, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: false, diagnostics: diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); // Regardless of whether __arglist appears in the source code, we do not mark // the operator method as being a varargs method. } returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics); // restricted types cannot be returned. // NOTE: Span-like types can be returned (if expression is returnable). if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } if (returnType.Type.IsStatic) { // Operators in interfaces was introduced in C# 8, so there's no need to be specially concerned about // maintaining backcompat with the native compiler bug around interfaces. // '{0}': static types cannot be used as return types diagnostics.Add(ErrorFacts.GetStaticClassReturnCode(useWarning: false), returnTypeSyntax.Location, returnType.Type); } return (returnType, parameters); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { var (returnType, parameters) = MakeParametersAndBindReturnType(diagnostics); MethodChecks(returnType, parameters, diagnostics); // If we have a static class then we already // have reported that fact as an error. No need to cascade the error further. if (this.ContainingType.IsStatic) { return; } CheckValueParameters(diagnostics); CheckOperatorSignatures(diagnostics); } protected abstract (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics); protected sealed override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics) { } protected sealed override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics) { if (_explicitInterfaceType is object) { string interfaceMethodName; ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier; switch (syntaxReferenceOpt.GetSyntax()) { case OperatorDeclarationSyntax operatorDeclaration: interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(operatorDeclaration); explicitInterfaceSpecifier = operatorDeclaration.ExplicitInterfaceSpecifier; break; case ConversionOperatorDeclarationSyntax conversionDeclaration: interfaceMethodName = OperatorFacts.OperatorNameFromDeclaration(conversionDeclaration); explicitInterfaceSpecifier = conversionDeclaration.ExplicitInterfaceSpecifier; break; default: throw ExceptionUtilities.Unreachable; } return this.FindExplicitlyImplementedMethod(isOperator: true, _explicitInterfaceType, interfaceMethodName, explicitInterfaceSpecifier, diagnostics); } return null; } #nullable enable protected sealed override TypeSymbol? ExplicitInterfaceType => _explicitInterfaceType; #nullable disable private void CheckValueParameters(BindingDiagnosticBag diagnostics) { // SPEC: The parameters of an operator must be value parameters. foreach (var p in this.Parameters) { if (p.RefKind != RefKind.None && p.RefKind != RefKind.In) { diagnostics.Add(ErrorCode.ERR_IllegalRefParam, this.Locations[0]); break; } } } private void CheckOperatorSignatures(BindingDiagnosticBag diagnostics) { if (MethodKind == MethodKind.ExplicitInterfaceImplementation) { // The signature is driven by the interface return; } // Have we even got the right formal parameter arity? If not then // we are in an error recovery scenario and we should just bail // out immediately. if (!DoesOperatorHaveCorrectArity(this.Name, this.ParameterCount)) { return; } switch (this.Name) { case WellKnownMemberNames.ImplicitConversionName: case WellKnownMemberNames.ExplicitConversionName: CheckUserDefinedConversionSignature(diagnostics); break; case WellKnownMemberNames.UnaryNegationOperatorName: case WellKnownMemberNames.UnaryPlusOperatorName: case WellKnownMemberNames.LogicalNotOperatorName: case WellKnownMemberNames.OnesComplementOperatorName: CheckUnarySignature(diagnostics); break; case WellKnownMemberNames.TrueOperatorName: case WellKnownMemberNames.FalseOperatorName: CheckTrueFalseSignature(diagnostics); break; case WellKnownMemberNames.IncrementOperatorName: case WellKnownMemberNames.DecrementOperatorName: CheckIncrementDecrementSignature(diagnostics); break; case WellKnownMemberNames.LeftShiftOperatorName: case WellKnownMemberNames.RightShiftOperatorName: CheckShiftSignature(diagnostics); break; default: CheckBinarySignature(diagnostics); break; } } private static bool DoesOperatorHaveCorrectArity(string name, int parameterCount) { switch (name) { case WellKnownMemberNames.IncrementOperatorName: case WellKnownMemberNames.DecrementOperatorName: case WellKnownMemberNames.UnaryNegationOperatorName: case WellKnownMemberNames.UnaryPlusOperatorName: case WellKnownMemberNames.LogicalNotOperatorName: case WellKnownMemberNames.OnesComplementOperatorName: case WellKnownMemberNames.TrueOperatorName: case WellKnownMemberNames.FalseOperatorName: case WellKnownMemberNames.ImplicitConversionName: case WellKnownMemberNames.ExplicitConversionName: return parameterCount == 1; default: return parameterCount == 2; } } private void CheckUserDefinedConversionSignature(BindingDiagnosticBag diagnostics) { if (this.ReturnsVoid) { // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } // SPEC: For a given source type S and target type T, if S or T are // SPEC: nullable types let S0 and T0 refer to their underlying types, // SPEC: otherwise, S0 and T0 are equal to S and T, respectively. var source = this.GetParameterType(0); var target = this.ReturnType; var source0 = source.StrippedType(); var target0 = target.StrippedType(); // SPEC: A class or struct is permitted to declare a conversion from S to T // SPEC: only if all the following are true: // SPEC: Neither S0 nor T0 is an interface type. if (source0.IsInterfaceType() || target0.IsInterfaceType()) { // CS0552: '{0}': user-defined conversions to or from an interface are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithInterface, this.Locations[0], this); return; } // SPEC: Either S0 or T0 is the class or struct type in which the operator // SPEC: declaration takes place. if (!MatchesContainingType(source0) && !MatchesContainingType(target0) && // allow conversion between T and Nullable<T> in declaration of Nullable<T> !MatchesContainingType(source) && !MatchesContainingType(target)) { // CS0556: User-defined conversion must convert to or from the enclosing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_AbstractConversionNotInvolvingContainedType : ErrorCode.ERR_ConversionNotInvolvingContainedType, this.Locations[0]); return; } // SPEC: * S0 and T0 are different types: if ((ContainingType.SpecialType == SpecialType.System_Nullable_T) ? source.Equals(target, ComparisonForUserDefinedOperators) : source0.Equals(target0, ComparisonForUserDefinedOperators)) { // CS0555: User-defined operator cannot convert a type to itself diagnostics.Add(ErrorCode.ERR_IdentityConversion, this.Locations[0]); return; } // Those are the easy ones. Now we come to: // SPEC: // Excluding user-defined conversions, a conversion does not exist from // S to T or T to S. For the purposes of these rules, any type parameters // associated with S or T are considered to be unique types that have // no inheritance relationship with other types, and any constraints on // those type parameters are ignored. // A counter-intuitive consequence of this rule is that: // // class X<U> where U : X<U> // { // public implicit operator X<U>(U u) { return u; } // } // // is *legal*, even though there is *already* an implicit conversion // from U to X<U> because U is constrained to have such a conversion. // // In discussing the implications of this rule, let's call the // containing type (which may be a class or struct) "C". S and T // are the source and target types. // // If we have made it this far in the error analysis we already know that // exactly one of S and T is C or C? -- if two or zero were, then we'd // have already reported ERR_ConversionNotInvolvingContainedType or // ERR_IdentityConversion and returned. // // WOLOG for the purposes of this discussion let's assume that S is // the one that is C or C?, and that T is the one that is neither C nor C?. // // So the question is: under what circumstances could T-to-S or S-to-T, // be a valid conversion, by the definition of valid above? // // Let's consider what kinds of types T could be. T cannot be an interface // because we've already reported an error and returned if it is. If T is // a delegate, array, enum, pointer, struct or nullable type then there // is no built-in conversion from T to the user-declared class/struct // C, or to C?. If T is a type parameter, then by assumption the type // parameter has no constraints, and therefore is not convertible to // C or C?. // // That leaves T to be a class. We already know that T is not C, (or C?, // since T is a class) and therefore there is no identity conversion from T to S. // // Suppose S is C and C is a class. Then the only way that there can be a // conversion between T and S is if T is a base class of S or S is a base class of T. // // Suppose S is C and C is a struct. Then the only way that there can be a // conversion between T and S is if T is a base class of S. (And T would // have to be System.Object or System.ValueType.) // // Suppose S is C? and C is a struct. Then the only way that there can be a // conversion between T and S is again, if T is a base class of S. // // Summing up: // // WOLOG, we assume that T is not C or C?, and S is C or C?. The conversion is // illegal only if T is a class, and either T is a base class of S, or S is a // base class of T. if (source.IsDynamic() || target.IsDynamic()) { // '{0}': user-defined conversions to or from the dynamic type are not allowed diagnostics.Add(ErrorCode.ERR_BadDynamicConversion, this.Locations[0], this); return; } TypeSymbol same; TypeSymbol different; if (MatchesContainingType(source0)) { same = source; different = target; } else { same = target; different = source; } if (different.IsClassType() && !same.IsTypeParameter()) { // different is a class type: Debug.Assert(!different.IsTypeParameter()); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (same.IsDerivedFrom(different, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)) { // '{0}': user-defined conversions to or from a base type are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithBase, this.Locations[0], this); } else if (different.IsDerivedFrom(same, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)) { // '{0}': user-defined conversions to or from a derived type are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithDerived, this.Locations[0], this); } diagnostics.Add(this.Locations[0], useSiteInfo); } } private void CheckUnarySignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary + - ! ~ operator must take a single parameter of type // SPEC: T or T? and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) { // The parameter of a unary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The Roslyn parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } private void CheckTrueFalseSignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary true or false operator must take a single parameter of type // SPEC: T or T? and must return type bool. if (this.ReturnType.SpecialType != SpecialType.System_Boolean) { // The return type of operator True or False must be bool diagnostics.Add(ErrorCode.ERR_OpTFRetType, this.Locations[0]); } if (!MatchesContainingType(this.GetParameterType(0).StrippedType())) { // The parameter of a unary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); } } private void CheckIncrementDecrementSignature(BindingDiagnosticBag diagnostics) { // SPEC: A unary ++ or -- operator must take a single parameter of type T or T? // SPEC: and it must return that same type or a type derived from it. // The native compiler error reporting behavior is not very good in some cases // here, both because it reports the wrong errors, and because the wording // of the error messages is misleading. The native compiler reports two errors: // CS0448: The return type for ++ or -- operator must be the // containing type or derived from the containing type // // CS0559: The parameter type for ++ or -- operator must be the containing type // // Neither error message mentions nullable types. But worse, there is a // situation in which the native compiler reports a misleading error: // // struct S { public static S operator ++(S? s) { ... } } // // This reports CS0559, but that is not the error; the *parameter* is perfectly // legal. The error is that the return type does not match the parameter type. // // I have changed the error message to reflect the true error, and we now // report 0448, not 0559, in the given scenario. The error is now: // // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type // // However, this now means that we must make *another* change from native compiler // behavior. The native compiler would report both 0448 and 0559 when given: // // struct S { public static int operator ++(int s) { ... } } // // The previous wording of error 0448 was *correct* in this scenario, but not // it is wrong because it *does* match the formal parameter type. // // The solution is: First see if 0559 must be reported. Only if the formal // parameter type is *good* do we then go on to try to report an error against // the return type. var parameterType = this.GetParameterType(0); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!MatchesContainingType(parameterType.StrippedType())) { // CS0559: The parameter type for ++ or -- operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractIncDecSignature : ErrorCode.ERR_BadIncDecSignature, this.Locations[0]); } else if (!(parameterType.IsTypeParameter() ? this.ReturnType.Equals(parameterType, ComparisonForUserDefinedOperators) : ((IsAbstract && IsContainingType(parameterType) && IsSelfConstrainedTypeParameter(this.ReturnType)) || this.ReturnType.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, ComparisonForUserDefinedOperators, useSiteInfo: ref useSiteInfo)))) { // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractIncDecRetType : ErrorCode.ERR_BadIncDecRetType, this.Locations[0]); } diagnostics.Add(this.Locations[0], useSiteInfo); } private bool MatchesContainingType(TypeSymbol type) { return IsContainingType(type) || (IsAbstract && IsSelfConstrainedTypeParameter(type)); } private bool IsContainingType(TypeSymbol type) { return type.Equals(this.ContainingType, ComparisonForUserDefinedOperators); } public static bool IsSelfConstrainedTypeParameter(TypeSymbol type, NamedTypeSymbol containingType) { Debug.Assert(containingType.IsDefinition); return type is TypeParameterSymbol p && // https://github.com/dotnet/roslyn/issues/53801: For now assuming the type parameter must belong to the containing type. (object)p.ContainingSymbol == containingType && // https://github.com/dotnet/roslyn/issues/53801: For now assume containing type must be one of the directly specified constraints. p.ConstraintTypesNoUseSiteDiagnostics.Any((typeArgument, containingType) => typeArgument.Type.Equals(containingType, ComparisonForUserDefinedOperators), containingType); } private bool IsSelfConstrainedTypeParameter(TypeSymbol type) { return IsSelfConstrainedTypeParameter(type, this.ContainingType); } private void CheckShiftSignature(BindingDiagnosticBag diagnostics) { // SPEC: A binary << or >> operator must take two parameters, the first // SPEC: of which must have type T or T? and the second of which must // SPEC: have type int or int?, and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType()) || this.GetParameterType(1).StrippedType().SpecialType != SpecialType.System_Int32) { // CS0546: The first operand of an overloaded shift operator must have the // same type as the containing type, and the type of the second // operand must be int diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadShiftOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The Roslyn parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } private void CheckBinarySignature(BindingDiagnosticBag diagnostics) { // SPEC: A binary nonshift operator must take two parameters, at least // SPEC: one of which must have the type T or T?, and can return any type. if (!MatchesContainingType(this.GetParameterType(0).StrippedType()) && !MatchesContainingType(this.GetParameterType(1).StrippedType())) { // CS0563: One of the parameters of a binary operator must be the containing type diagnostics.Add(IsAbstract ? ErrorCode.ERR_BadAbstractBinaryOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature, this.Locations[0]); } if (this.ReturnsVoid) { // The parser does not detect this error. // CS0590: User-defined operators cannot return void diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]); } } public sealed override string Name { get { return _name; } } public sealed override bool IsVararg { get { return false; } } public sealed override bool IsExtensionMethod { get { return false; } } public sealed override ImmutableArray<Location> Locations { get { return this.locations; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public sealed override RefKind RefKind { get { return RefKind.None; } } internal sealed override bool IsExpressionBodied { get { return _isExpressionBodied; } } protected sealed override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { if ((object)_explicitInterfaceType != null) { NameSyntax name; switch (syntaxReferenceOpt.GetSyntax()) { case OperatorDeclarationSyntax operatorDeclaration: Debug.Assert(operatorDeclaration.ExplicitInterfaceSpecifier != null); name = operatorDeclaration.ExplicitInterfaceSpecifier.Name; break; case ConversionOperatorDeclarationSyntax conversionDeclaration: Debug.Assert(conversionDeclaration.ExplicitInterfaceSpecifier != null); name = conversionDeclaration.ExplicitInterfaceSpecifier.Name; break; default: throw ExceptionUtilities.Unreachable; } _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(name), diagnostics); } } protected sealed override void PartialMethodChecks(BindingDiagnosticBag diagnostics) { } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEAssemblySymbol.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.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Linq.Enumerable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Represents an assembly imported from a PE. ''' </summary> ''' <remarks></remarks> Friend NotInheritable Class PEAssemblySymbol Inherits MetadataOrSourceAssemblySymbol ''' <summary> ''' An Assembly object providing metadata for the assembly. ''' </summary> ''' <remarks></remarks> Private ReadOnly _assembly As PEAssembly ''' <summary> ''' A MetadataDocumentationProvider providing XML documentation for this assembly. ''' </summary> Private ReadOnly _documentationProvider As DocumentationProvider ''' <summary> ''' The list of contained PEModuleSymbol objects. ''' The list doesn't use type ReadOnlyCollection(Of PEModuleSymbol) so that we ''' can return it from Modules property as is. ''' </summary> ''' <remarks></remarks> Private ReadOnly _modules As ImmutableArray(Of ModuleSymbol) ''' <summary> ''' An array of assemblies involved in canonical type resolution of ''' NoPia local types defined within this assembly. In other words, all ''' references used by a compilation referencing this assembly. ''' The array and its content is provided by ReferenceManager and must not be modified. ''' </summary> Private _noPiaResolutionAssemblies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' An array of assemblies referenced by this assembly, which are linked (/l-ed) by ''' each compilation that is using this AssemblySymbol as a reference. ''' If this AssemblySymbol is linked too, it will be in this array too. ''' The array and its content is provided by ReferenceManager and must not be modified. ''' </summary> Private _linkedReferencedAssemblies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' Assembly is /l-ed by compilation that is using it as a reference. ''' </summary> Private ReadOnly _isLinked As Boolean Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Friend Sub New(assembly As PEAssembly, documentationProvider As DocumentationProvider, isLinked As Boolean, importOptions As MetadataImportOptions) Debug.Assert(assembly IsNot Nothing) _assembly = assembly _documentationProvider = documentationProvider Dim modules(assembly.Modules.Length - 1) As ModuleSymbol For i As Integer = 0 To assembly.Modules.Length - 1 Step 1 modules(i) = New PEModuleSymbol(Me, assembly.Modules(i), importOptions, i) Next _modules = modules.AsImmutableOrNull() _isLinked = isLinked End Sub Friend ReadOnly Property Assembly As PEAssembly Get Return _assembly End Get End Property Public Overrides ReadOnly Property Identity As AssemblyIdentity Get Return _assembly.Identity End Get End Property Public Overrides ReadOnly Property AssemblyVersionPattern As Version Get ' TODO: https://github.com/dotnet/roslyn/issues/9000 Return Nothing End Get End Property Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte) Get Return _assembly.Identity.PublicKey End Get End Property Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean Return Assembly.Modules(0).HasGuidAttribute(Assembly.Handle, guidString) End Function Friend Overrides Function AreInternalsVisibleToThisAssembly(potentialGiverOfAccess As AssemblySymbol) As Boolean Return MakeFinalIVTDetermination(potentialGiverOfAccess) = IVTConclusion.Match End Function Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte)) Return Assembly.GetInternalsVisibleToPublicKeys(simpleName) End Function Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then PrimaryModule.LoadCustomAttributes(Me.Assembly.Handle, _lazyCustomAttributes) End If Return _lazyCustomAttributes End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(PrimaryModule.MetadataLocation) End Get End Property Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol) Get Return _modules End Get End Property Friend ReadOnly Property PrimaryModule As PEModuleSymbol Get Return DirectCast(Me.Modules(0), PEModuleSymbol) End Get End Property ''' <summary> ''' Look up the assemblies to which the given metadata type Is forwarded. ''' </summary> ''' <param name="emittedName"></param> ''' <param name="ignoreCase">Pass true to look up fullName case-insensitively. WARNING: more expensive.</param> ''' <param name="matchedName">Returns the actual casing of the matching name.</param> ''' <returns> ''' The assemblies to which the given type Is forwarded Or null, if there isn't one. ''' </returns> ''' <remarks> ''' The returned assemblies may also forward the type. ''' </remarks> Friend Function LookupAssembliesForForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean, <Out> ByRef matchedName As String) As (FirstSymbol As AssemblySymbol, SecondSymbol As AssemblySymbol) ' Look in the type forwarders of the primary module of this assembly, clr does not honor type forwarder ' in non-primary modules. ' Examine the type forwarders, but only from the primary module. Return PrimaryModule.GetAssembliesForForwardedType(emittedName, ignoreCase, matchedName) End Function Friend Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol) Return PrimaryModule.GetForwardedTypes() End Function Friend Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ' Check if it is a forwarded type. Dim matchedName As String = Nothing Dim forwardedToAssemblies = LookupAssembliesForForwardedMetadataType(emittedName, ignoreCase, matchedName) If forwardedToAssemblies.FirstSymbol IsNot Nothing Then If forwardedToAssemblies.SecondSymbol IsNot Nothing Then ' Report the main module as that is the only one checked. clr does not honor type forwarders in non-primary modules. Return CreateMultipleForwardingErrorTypeSymbol(emittedName, PrimaryModule, forwardedToAssemblies.FirstSymbol, forwardedToAssemblies.SecondSymbol) End If ' Don't bother to check the forwarded-to assembly if we've already seen it. If visitedAssemblies IsNot Nothing AndAlso visitedAssemblies.Contains(forwardedToAssemblies.FirstSymbol) Then Return CreateCycleInTypeForwarderErrorTypeSymbol(emittedName) Else visitedAssemblies = New ConsList(Of AssemblySymbol)(Me, If(visitedAssemblies, ConsList(Of AssemblySymbol).Empty)) If ignoreCase AndAlso Not String.Equals(emittedName.FullName, matchedName, StringComparison.Ordinal) Then emittedName = MetadataTypeName.FromFullName(matchedName, emittedName.UseCLSCompliantNameArityEncoding, emittedName.ForcedArity) End If Return forwardedToAssemblies.FirstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, digThroughForwardedTypes:=True) End If End If Return Nothing End Function Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol) Return _noPiaResolutionAssemblies End Function Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) _noPiaResolutionAssemblies = assemblies End Sub Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) _linkedReferencedAssemblies = assemblies End Sub Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol) Return _linkedReferencedAssemblies End Function Friend Overrides ReadOnly Property IsLinked As Boolean Get Return _isLinked End Get End Property Friend ReadOnly Property DocumentationProvider As DocumentationProvider Get Return _documentationProvider End Get End Property Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get If _lazyMightContainExtensionMethods = ThreeState.Unknown Then Dim primaryModuleSymbol = PrimaryModule If primaryModuleSymbol.Module.HasExtensionAttribute(_assembly.Handle, ignoreCase:=True) Then _lazyMightContainExtensionMethods = ThreeState.True Else _lazyMightContainExtensionMethods = ThreeState.False End If End If Return _lazyMightContainExtensionMethods = ThreeState.True End Get End Property ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property Public Overrides Function GetMetadata() As AssemblyMetadata Return _assembly.GetNonDisposableMetadata() 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.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Linq.Enumerable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Represents an assembly imported from a PE. ''' </summary> ''' <remarks></remarks> Friend NotInheritable Class PEAssemblySymbol Inherits MetadataOrSourceAssemblySymbol ''' <summary> ''' An Assembly object providing metadata for the assembly. ''' </summary> ''' <remarks></remarks> Private ReadOnly _assembly As PEAssembly ''' <summary> ''' A MetadataDocumentationProvider providing XML documentation for this assembly. ''' </summary> Private ReadOnly _documentationProvider As DocumentationProvider ''' <summary> ''' The list of contained PEModuleSymbol objects. ''' The list doesn't use type ReadOnlyCollection(Of PEModuleSymbol) so that we ''' can return it from Modules property as is. ''' </summary> ''' <remarks></remarks> Private ReadOnly _modules As ImmutableArray(Of ModuleSymbol) ''' <summary> ''' An array of assemblies involved in canonical type resolution of ''' NoPia local types defined within this assembly. In other words, all ''' references used by a compilation referencing this assembly. ''' The array and its content is provided by ReferenceManager and must not be modified. ''' </summary> Private _noPiaResolutionAssemblies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' An array of assemblies referenced by this assembly, which are linked (/l-ed) by ''' each compilation that is using this AssemblySymbol as a reference. ''' If this AssemblySymbol is linked too, it will be in this array too. ''' The array and its content is provided by ReferenceManager and must not be modified. ''' </summary> Private _linkedReferencedAssemblies As ImmutableArray(Of AssemblySymbol) ''' <summary> ''' Assembly is /l-ed by compilation that is using it as a reference. ''' </summary> Private ReadOnly _isLinked As Boolean Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) Friend Sub New(assembly As PEAssembly, documentationProvider As DocumentationProvider, isLinked As Boolean, importOptions As MetadataImportOptions) Debug.Assert(assembly IsNot Nothing) _assembly = assembly _documentationProvider = documentationProvider Dim modules(assembly.Modules.Length - 1) As ModuleSymbol For i As Integer = 0 To assembly.Modules.Length - 1 Step 1 modules(i) = New PEModuleSymbol(Me, assembly.Modules(i), importOptions, i) Next _modules = modules.AsImmutableOrNull() _isLinked = isLinked End Sub Friend ReadOnly Property Assembly As PEAssembly Get Return _assembly End Get End Property Public Overrides ReadOnly Property Identity As AssemblyIdentity Get Return _assembly.Identity End Get End Property Public Overrides ReadOnly Property AssemblyVersionPattern As Version Get ' TODO: https://github.com/dotnet/roslyn/issues/9000 Return Nothing End Get End Property Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte) Get Return _assembly.Identity.PublicKey End Get End Property Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean Return Assembly.Modules(0).HasGuidAttribute(Assembly.Handle, guidString) End Function Friend Overrides Function AreInternalsVisibleToThisAssembly(potentialGiverOfAccess As AssemblySymbol) As Boolean Return MakeFinalIVTDetermination(potentialGiverOfAccess) = IVTConclusion.Match End Function Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte)) Return Assembly.GetInternalsVisibleToPublicKeys(simpleName) End Function Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then PrimaryModule.LoadCustomAttributes(Me.Assembly.Handle, _lazyCustomAttributes) End If Return _lazyCustomAttributes End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return StaticCast(Of Location).From(PrimaryModule.MetadataLocation) End Get End Property Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol) Get Return _modules End Get End Property Friend ReadOnly Property PrimaryModule As PEModuleSymbol Get Return DirectCast(Me.Modules(0), PEModuleSymbol) End Get End Property ''' <summary> ''' Look up the assemblies to which the given metadata type Is forwarded. ''' </summary> ''' <param name="emittedName"></param> ''' <param name="ignoreCase">Pass true to look up fullName case-insensitively. WARNING: more expensive.</param> ''' <param name="matchedName">Returns the actual casing of the matching name.</param> ''' <returns> ''' The assemblies to which the given type Is forwarded Or null, if there isn't one. ''' </returns> ''' <remarks> ''' The returned assemblies may also forward the type. ''' </remarks> Friend Function LookupAssembliesForForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean, <Out> ByRef matchedName As String) As (FirstSymbol As AssemblySymbol, SecondSymbol As AssemblySymbol) ' Look in the type forwarders of the primary module of this assembly, clr does not honor type forwarder ' in non-primary modules. ' Examine the type forwarders, but only from the primary module. Return PrimaryModule.GetAssembliesForForwardedType(emittedName, ignoreCase, matchedName) End Function Friend Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol) Return PrimaryModule.GetForwardedTypes() End Function Friend Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ' Check if it is a forwarded type. Dim matchedName As String = Nothing Dim forwardedToAssemblies = LookupAssembliesForForwardedMetadataType(emittedName, ignoreCase, matchedName) If forwardedToAssemblies.FirstSymbol IsNot Nothing Then If forwardedToAssemblies.SecondSymbol IsNot Nothing Then ' Report the main module as that is the only one checked. clr does not honor type forwarders in non-primary modules. Return CreateMultipleForwardingErrorTypeSymbol(emittedName, PrimaryModule, forwardedToAssemblies.FirstSymbol, forwardedToAssemblies.SecondSymbol) End If ' Don't bother to check the forwarded-to assembly if we've already seen it. If visitedAssemblies IsNot Nothing AndAlso visitedAssemblies.Contains(forwardedToAssemblies.FirstSymbol) Then Return CreateCycleInTypeForwarderErrorTypeSymbol(emittedName) Else visitedAssemblies = New ConsList(Of AssemblySymbol)(Me, If(visitedAssemblies, ConsList(Of AssemblySymbol).Empty)) If ignoreCase AndAlso Not String.Equals(emittedName.FullName, matchedName, StringComparison.Ordinal) Then emittedName = MetadataTypeName.FromFullName(matchedName, emittedName.UseCLSCompliantNameArityEncoding, emittedName.ForcedArity) End If Return forwardedToAssemblies.FirstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, digThroughForwardedTypes:=True) End If End If Return Nothing End Function Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol) Return _noPiaResolutionAssemblies End Function Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) _noPiaResolutionAssemblies = assemblies End Sub Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol)) _linkedReferencedAssemblies = assemblies End Sub Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol) Return _linkedReferencedAssemblies End Function Friend Overrides ReadOnly Property IsLinked As Boolean Get Return _isLinked End Get End Property Friend ReadOnly Property DocumentationProvider As DocumentationProvider Get Return _documentationProvider End Get End Property Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get If _lazyMightContainExtensionMethods = ThreeState.Unknown Then Dim primaryModuleSymbol = PrimaryModule If primaryModuleSymbol.Module.HasExtensionAttribute(_assembly.Handle, ignoreCase:=True) Then _lazyMightContainExtensionMethods = ThreeState.True Else _lazyMightContainExtensionMethods = ThreeState.False End If End If Return _lazyMightContainExtensionMethods = ThreeState.True End Get End Property ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property Public Overrides Function GetMetadata() As AssemblyMetadata Return _assembly.GetNonDisposableMetadata() End Function End Class End Namespace
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Workspaces/Remote/ServiceHub/Services/DiagnosticAnalyzer/PerformanceQueue.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Diagnostics { /// <summary> /// This queue hold onto raw performance data. this type itself is not thread safe. the one who uses this type /// should take care of that. /// </summary> /// <threadsafety static="false" instance="false"/> internal class PerformanceQueue { // we need at least 100 samples for result to be stable private const int MinSampleSize = 100; private readonly int _maxSampleSize; private readonly LinkedList<Snapshot> _snapshots; public PerformanceQueue(int maxSampleSize) { Contract.ThrowIfFalse(maxSampleSize > MinSampleSize); _maxSampleSize = maxSampleSize; _snapshots = new LinkedList<Snapshot>(); } public int Count => _snapshots.Count; public void Add(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData, int unitCount) { if (_snapshots.Count < _maxSampleSize) { _snapshots.AddLast(new Snapshot(rawData, unitCount)); } else { // remove the first one var first = _snapshots.First; _snapshots.RemoveFirst(); // update data to new data and put it back first.Value.Update(rawData, unitCount); _snapshots.AddLast(first); } } public void GetPerformanceData(Dictionary<string, (double average, double stddev)> aggregatedPerformanceDataPerAnalyzer) { if (_snapshots.Count < MinSampleSize) { // we don't have enough data to report this return; } using var pooledMap = SharedPools.Default<Dictionary<int, string>>().GetPooledObject(); using var pooledSet = SharedPools.Default<HashSet<int>>().GetPooledObject(); using var pooledList = SharedPools.Default<List<double>>().GetPooledObject(); var reverseMap = pooledMap.Object; AnalyzerNumberAssigner.Instance.GetReverseMap(reverseMap); var analyzerSet = pooledSet.Object; // get all analyzers foreach (var snapshot in _snapshots) { snapshot.AppendAnalyzers(analyzerSet); } var list = pooledList.Object; // calculate aggregated data per analyzer foreach (var assignedAnalyzerNumber in analyzerSet) { foreach (var snapshot in _snapshots) { var timeSpan = snapshot.GetTimeSpanInMillisecond(assignedAnalyzerNumber); if (timeSpan == null) { // not all snapshot contains all analyzers continue; } list.Add(timeSpan.Value); } // data is only stable once we have more than certain set // of samples if (list.Count < MinSampleSize) { continue; } // set performance data aggregatedPerformanceDataPerAnalyzer[reverseMap[assignedAnalyzerNumber]] = GetAverageAndAdjustedStandardDeviation(list); list.Clear(); } } private static (double average, double stddev) GetAverageAndAdjustedStandardDeviation(List<double> data) { var average = data.Average(); var stddev = Math.Sqrt(data.Select(ms => Math.Pow(ms - average, 2)).Average()); var squareLength = Math.Sqrt(data.Count); return (average, stddev / squareLength); } private class Snapshot { /// <summary> /// Raw performance data. /// Keyed by analyzer unique number got from AnalyzerNumberAssigner. /// Value is delta (TimeSpan - minSpan) among span in this snapshot /// </summary> private readonly Dictionary<int, double> _performanceMap; public Snapshot(IEnumerable<(string analyzerId, TimeSpan timeSpan)> snapshot, int unitCount) : this(Convert(snapshot), unitCount) { } public Snapshot(IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> rawData, int unitCount) { _performanceMap = new Dictionary<int, double>(); Reset(_performanceMap, rawData, unitCount); } public void Update(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData, int unitCount) => Reset(_performanceMap, Convert(rawData), unitCount); public void AppendAnalyzers(HashSet<int> analyzerSet) => analyzerSet.UnionWith(_performanceMap.Keys); public double? GetTimeSpanInMillisecond(int assignedAnalyzerNumber) { if (!_performanceMap.TryGetValue(assignedAnalyzerNumber, out var value)) { return null; } return value; } private static void Reset( Dictionary<int, double> map, IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> rawData, int fileCount) { // get smallest timespan in the snapshot var minSpan = rawData.Select(kv => kv.timeSpan).Min(); // for now, we just clear the map, if reusing dictionary blindly became an issue due to // dictionary grew too big, then we need to do a bit more work to determine such case // and re-create new dictionary map.Clear(); // map is normalized to current timespan - min timspan of the snapshot foreach (var (assignedAnalyzerNumber, timeSpan) in rawData) { map[assignedAnalyzerNumber] = (timeSpan.TotalMilliseconds - minSpan.TotalMilliseconds) / fileCount; } } private static IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> Convert(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData) => rawData.Select(kv => (AnalyzerNumberAssigner.Instance.GetUniqueNumber(kv.analyzerId), kv.timeSpan)); } /// <summary> /// Assign unique number to diagnostic analyzers /// </summary> private class AnalyzerNumberAssigner { public static readonly AnalyzerNumberAssigner Instance = new AnalyzerNumberAssigner(); private int _currentId; // use simple approach for now. we don't expect it to grow too much. so entry added // won't be removed until process goes away private readonly Dictionary<string, int> _idMap; private AnalyzerNumberAssigner() { _currentId = 0; _idMap = new Dictionary<string, int>(); } public int GetUniqueNumber(DiagnosticAnalyzer analyzer) => GetUniqueNumber(analyzer.GetAnalyzerId()); public int GetUniqueNumber(string analyzerName) { if (!_idMap.TryGetValue(analyzerName, out var id)) { id = _currentId++; _idMap.Add(analyzerName, id); } return id; } public void GetReverseMap(Dictionary<int, string> reverseMap) { reverseMap.Clear(); foreach (var kv in _idMap) { reverseMap.Add(kv.Value, kv.Key); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Diagnostics { /// <summary> /// This queue hold onto raw performance data. this type itself is not thread safe. the one who uses this type /// should take care of that. /// </summary> /// <threadsafety static="false" instance="false"/> internal class PerformanceQueue { // we need at least 100 samples for result to be stable private const int MinSampleSize = 100; private readonly int _maxSampleSize; private readonly LinkedList<Snapshot> _snapshots; public PerformanceQueue(int maxSampleSize) { Contract.ThrowIfFalse(maxSampleSize > MinSampleSize); _maxSampleSize = maxSampleSize; _snapshots = new LinkedList<Snapshot>(); } public int Count => _snapshots.Count; public void Add(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData, int unitCount) { if (_snapshots.Count < _maxSampleSize) { _snapshots.AddLast(new Snapshot(rawData, unitCount)); } else { // remove the first one var first = _snapshots.First; _snapshots.RemoveFirst(); // update data to new data and put it back first.Value.Update(rawData, unitCount); _snapshots.AddLast(first); } } public void GetPerformanceData(Dictionary<string, (double average, double stddev)> aggregatedPerformanceDataPerAnalyzer) { if (_snapshots.Count < MinSampleSize) { // we don't have enough data to report this return; } using var pooledMap = SharedPools.Default<Dictionary<int, string>>().GetPooledObject(); using var pooledSet = SharedPools.Default<HashSet<int>>().GetPooledObject(); using var pooledList = SharedPools.Default<List<double>>().GetPooledObject(); var reverseMap = pooledMap.Object; AnalyzerNumberAssigner.Instance.GetReverseMap(reverseMap); var analyzerSet = pooledSet.Object; // get all analyzers foreach (var snapshot in _snapshots) { snapshot.AppendAnalyzers(analyzerSet); } var list = pooledList.Object; // calculate aggregated data per analyzer foreach (var assignedAnalyzerNumber in analyzerSet) { foreach (var snapshot in _snapshots) { var timeSpan = snapshot.GetTimeSpanInMillisecond(assignedAnalyzerNumber); if (timeSpan == null) { // not all snapshot contains all analyzers continue; } list.Add(timeSpan.Value); } // data is only stable once we have more than certain set // of samples if (list.Count < MinSampleSize) { continue; } // set performance data aggregatedPerformanceDataPerAnalyzer[reverseMap[assignedAnalyzerNumber]] = GetAverageAndAdjustedStandardDeviation(list); list.Clear(); } } private static (double average, double stddev) GetAverageAndAdjustedStandardDeviation(List<double> data) { var average = data.Average(); var stddev = Math.Sqrt(data.Select(ms => Math.Pow(ms - average, 2)).Average()); var squareLength = Math.Sqrt(data.Count); return (average, stddev / squareLength); } private class Snapshot { /// <summary> /// Raw performance data. /// Keyed by analyzer unique number got from AnalyzerNumberAssigner. /// Value is delta (TimeSpan - minSpan) among span in this snapshot /// </summary> private readonly Dictionary<int, double> _performanceMap; public Snapshot(IEnumerable<(string analyzerId, TimeSpan timeSpan)> snapshot, int unitCount) : this(Convert(snapshot), unitCount) { } public Snapshot(IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> rawData, int unitCount) { _performanceMap = new Dictionary<int, double>(); Reset(_performanceMap, rawData, unitCount); } public void Update(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData, int unitCount) => Reset(_performanceMap, Convert(rawData), unitCount); public void AppendAnalyzers(HashSet<int> analyzerSet) => analyzerSet.UnionWith(_performanceMap.Keys); public double? GetTimeSpanInMillisecond(int assignedAnalyzerNumber) { if (!_performanceMap.TryGetValue(assignedAnalyzerNumber, out var value)) { return null; } return value; } private static void Reset( Dictionary<int, double> map, IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> rawData, int fileCount) { // get smallest timespan in the snapshot var minSpan = rawData.Select(kv => kv.timeSpan).Min(); // for now, we just clear the map, if reusing dictionary blindly became an issue due to // dictionary grew too big, then we need to do a bit more work to determine such case // and re-create new dictionary map.Clear(); // map is normalized to current timespan - min timspan of the snapshot foreach (var (assignedAnalyzerNumber, timeSpan) in rawData) { map[assignedAnalyzerNumber] = (timeSpan.TotalMilliseconds - minSpan.TotalMilliseconds) / fileCount; } } private static IEnumerable<(int assignedAnalyzerNumber, TimeSpan timeSpan)> Convert(IEnumerable<(string analyzerId, TimeSpan timeSpan)> rawData) => rawData.Select(kv => (AnalyzerNumberAssigner.Instance.GetUniqueNumber(kv.analyzerId), kv.timeSpan)); } /// <summary> /// Assign unique number to diagnostic analyzers /// </summary> private class AnalyzerNumberAssigner { public static readonly AnalyzerNumberAssigner Instance = new AnalyzerNumberAssigner(); private int _currentId; // use simple approach for now. we don't expect it to grow too much. so entry added // won't be removed until process goes away private readonly Dictionary<string, int> _idMap; private AnalyzerNumberAssigner() { _currentId = 0; _idMap = new Dictionary<string, int>(); } public int GetUniqueNumber(DiagnosticAnalyzer analyzer) => GetUniqueNumber(analyzer.GetAnalyzerId()); public int GetUniqueNumber(string analyzerName) { if (!_idMap.TryGetValue(analyzerName, out var id)) { id = _currentId++; _idMap.Add(analyzerName, id); } return id; } public void GetReverseMap(Dictionary<int, string> reverseMap) { reverseMap.Clear(); foreach (var kv in _idMap) { reverseMap.Add(kv.Value, kv.Key); } } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Core/Portable/PEWriter/MemberRefComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MemberRefComparer : IEqualityComparer<ITypeMemberReference> { private readonly MetadataWriter _metadataWriter; internal MemberRefComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(ITypeMemberReference? x, ITypeMemberReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); if (x.GetContainingType(_metadataWriter.Context) != y.GetContainingType(_metadataWriter.Context)) { if (_metadataWriter.GetMemberReferenceParent(x) != _metadataWriter.GetMemberReferenceParent(y)) { return false; } } if (x.Name != y.Name) { return false; } var xf = x as IFieldReference; var yf = y as IFieldReference; if (xf != null && yf != null) { return _metadataWriter.GetFieldSignatureIndex(xf) == _metadataWriter.GetFieldSignatureIndex(yf); } var xm = x as IMethodReference; var ym = y as IMethodReference; if (xm != null && ym != null) { return _metadataWriter.GetMethodSignatureHandle(xm) == _metadataWriter.GetMethodSignatureHandle(ym); } return false; } public int GetHashCode(ITypeMemberReference memberRef) { int hash = Hash.Combine(memberRef.Name, _metadataWriter.GetMemberReferenceParent(memberRef).GetHashCode()); var fieldRef = memberRef as IFieldReference; if (fieldRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetFieldSignatureIndex(fieldRef).GetHashCode()); } else { var methodRef = memberRef as IMethodReference; if (methodRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetMethodSignatureHandle(methodRef).GetHashCode()); } } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MemberRefComparer : IEqualityComparer<ITypeMemberReference> { private readonly MetadataWriter _metadataWriter; internal MemberRefComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(ITypeMemberReference? x, ITypeMemberReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); if (x.GetContainingType(_metadataWriter.Context) != y.GetContainingType(_metadataWriter.Context)) { if (_metadataWriter.GetMemberReferenceParent(x) != _metadataWriter.GetMemberReferenceParent(y)) { return false; } } if (x.Name != y.Name) { return false; } var xf = x as IFieldReference; var yf = y as IFieldReference; if (xf != null && yf != null) { return _metadataWriter.GetFieldSignatureIndex(xf) == _metadataWriter.GetFieldSignatureIndex(yf); } var xm = x as IMethodReference; var ym = y as IMethodReference; if (xm != null && ym != null) { return _metadataWriter.GetMethodSignatureHandle(xm) == _metadataWriter.GetMethodSignatureHandle(ym); } return false; } public int GetHashCode(ITypeMemberReference memberRef) { int hash = Hash.Combine(memberRef.Name, _metadataWriter.GetMemberReferenceParent(memberRef).GetHashCode()); var fieldRef = memberRef as IFieldReference; if (fieldRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetFieldSignatureIndex(fieldRef).GetHashCode()); } else { var methodRef = memberRef as IMethodReference; if (methodRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetMethodSignatureHandle(methodRef).GetHashCode()); } } return hash; } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer { internal const string DocCommentIdKey = nameof(DocCommentIdKey); private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Invalid_global_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidScopeMessage = new( nameof(AnalyzersResources.Invalid_scope_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidOrMissingTargetMessage = new( nameof(AnalyzersResources.Invalid_or_missing_target_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly DiagnosticDescriptor s_invalidScopeDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidScopeMessage, isUnnecessary: true); private static readonly DiagnosticDescriptor s_invalidOrMissingTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidOrMissingTargetMessage, isUnnecessary: true); private static readonly LocalizableResourceString s_localizableLegacyFormatTitle = new( nameof(AnalyzersResources.Avoid_legacy_format_target_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableLegacyFormatMessage = new( nameof(AnalyzersResources.Avoid_legacy_format_target_0_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor LegacyFormatTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.LegacyFormatSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.LegacyFormatSuppressMessageAttribute, s_localizableLegacyFormatTitle, s_localizableLegacyFormatMessage, isUnnecessary: false); protected AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_invalidScopeDescriptor, s_invalidOrMissingTargetDescriptor, LegacyFormatTargetDescriptor), GeneratedCodeAnalysisFlags.None) { } protected abstract void RegisterAttributeSyntaxAction(CompilationStartAnalysisContext context, CompilationAnalyzer compilationAnalyzer); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { var suppressMessageAttributeType = context.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return; } RegisterAttributeSyntaxAction(context, new CompilationAnalyzer(context.Compilation, suppressMessageAttributeType)); }); } protected sealed class CompilationAnalyzer { private readonly SuppressMessageAttributeState _state; public CompilationAnalyzer(Compilation compilation, INamedTypeSymbol suppressMessageAttributeType) { _state = new SuppressMessageAttributeState(compilation, suppressMessageAttributeType); } public void AnalyzeAssemblyOrModuleAttribute(SyntaxNode attributeSyntax, SemanticModel model, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { if (!_state.IsSuppressMessageAttributeWithNamedArguments(attributeSyntax, model, cancellationToken, out var namedAttributeArguments)) { return; } if (!SuppressMessageAttributeState.HasValidScope(namedAttributeArguments, out var targetScope)) { reportDiagnostic(Diagnostic.Create(s_invalidScopeDescriptor, attributeSyntax.GetLocation())); return; } if (!_state.HasValidTarget(namedAttributeArguments, targetScope, out var targetHasDocCommentIdFormat, out var targetSymbolString, out var targetValueOperation, out var resolvedSymbols)) { reportDiagnostic(Diagnostic.Create(s_invalidOrMissingTargetDescriptor, attributeSyntax.GetLocation())); return; } // We want to flag valid target which uses legacy format to update to Roslyn based DocCommentId format. if (resolvedSymbols.Length > 0 && !targetHasDocCommentIdFormat) { RoslynDebug.Assert(!string.IsNullOrEmpty(targetSymbolString)); RoslynDebug.Assert(targetValueOperation != null); var properties = ImmutableDictionary<string, string?>.Empty; if (resolvedSymbols.Length == 1) { // We provide a code fix for the case where the target resolved to a single symbol. var docCommentId = DocumentationCommentId.CreateDeclarationId(resolvedSymbols[0]); if (!string.IsNullOrEmpty(docCommentId)) { // Suppression target has an optional "~" prefix to distinguish it from legacy FxCop suppressions. // IDE suppression code fixes emit this prefix, so we we also add this prefix to new suppression target string. properties = properties.Add(DocCommentIdKey, "~" + docCommentId); } } reportDiagnostic(Diagnostic.Create(LegacyFormatTargetDescriptor, targetValueOperation.Syntax.GetLocation(), properties!, targetSymbolString)); return; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer { internal const string DocCommentIdKey = nameof(DocCommentIdKey); private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Invalid_global_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidScopeMessage = new( nameof(AnalyzersResources.Invalid_scope_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidOrMissingTargetMessage = new( nameof(AnalyzersResources.Invalid_or_missing_target_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly DiagnosticDescriptor s_invalidScopeDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidScopeMessage, isUnnecessary: true); private static readonly DiagnosticDescriptor s_invalidOrMissingTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidOrMissingTargetMessage, isUnnecessary: true); private static readonly LocalizableResourceString s_localizableLegacyFormatTitle = new( nameof(AnalyzersResources.Avoid_legacy_format_target_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableLegacyFormatMessage = new( nameof(AnalyzersResources.Avoid_legacy_format_target_0_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor LegacyFormatTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.LegacyFormatSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.LegacyFormatSuppressMessageAttribute, s_localizableLegacyFormatTitle, s_localizableLegacyFormatMessage, isUnnecessary: false); protected AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_invalidScopeDescriptor, s_invalidOrMissingTargetDescriptor, LegacyFormatTargetDescriptor), GeneratedCodeAnalysisFlags.None) { } protected abstract void RegisterAttributeSyntaxAction(CompilationStartAnalysisContext context, CompilationAnalyzer compilationAnalyzer); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { var suppressMessageAttributeType = context.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return; } RegisterAttributeSyntaxAction(context, new CompilationAnalyzer(context.Compilation, suppressMessageAttributeType)); }); } protected sealed class CompilationAnalyzer { private readonly SuppressMessageAttributeState _state; public CompilationAnalyzer(Compilation compilation, INamedTypeSymbol suppressMessageAttributeType) { _state = new SuppressMessageAttributeState(compilation, suppressMessageAttributeType); } public void AnalyzeAssemblyOrModuleAttribute(SyntaxNode attributeSyntax, SemanticModel model, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { if (!_state.IsSuppressMessageAttributeWithNamedArguments(attributeSyntax, model, cancellationToken, out var namedAttributeArguments)) { return; } if (!SuppressMessageAttributeState.HasValidScope(namedAttributeArguments, out var targetScope)) { reportDiagnostic(Diagnostic.Create(s_invalidScopeDescriptor, attributeSyntax.GetLocation())); return; } if (!_state.HasValidTarget(namedAttributeArguments, targetScope, out var targetHasDocCommentIdFormat, out var targetSymbolString, out var targetValueOperation, out var resolvedSymbols)) { reportDiagnostic(Diagnostic.Create(s_invalidOrMissingTargetDescriptor, attributeSyntax.GetLocation())); return; } // We want to flag valid target which uses legacy format to update to Roslyn based DocCommentId format. if (resolvedSymbols.Length > 0 && !targetHasDocCommentIdFormat) { RoslynDebug.Assert(!string.IsNullOrEmpty(targetSymbolString)); RoslynDebug.Assert(targetValueOperation != null); var properties = ImmutableDictionary<string, string?>.Empty; if (resolvedSymbols.Length == 1) { // We provide a code fix for the case where the target resolved to a single symbol. var docCommentId = DocumentationCommentId.CreateDeclarationId(resolvedSymbols[0]); if (!string.IsNullOrEmpty(docCommentId)) { // Suppression target has an optional "~" prefix to distinguish it from legacy FxCop suppressions. // IDE suppression code fixes emit this prefix, so we we also add this prefix to new suppression target string. properties = properties.Add(DocCommentIdKey, "~" + docCommentId); } } reportDiagnostic(Diagnostic.Create(LegacyFormatTargetDescriptor, targetValueOperation.Syntax.GetLocation(), properties!, targetSymbolString)); return; } } } } }
-1
dotnet/roslyn
55,718
EnC - Parameterless struct constructors
Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
davidwengier
2021-08-19T05:52:57Z
2021-08-20T04:50:31Z
7c6289ac905f702fa4398067b91cf29a80e4692a
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
EnC - Parameterless struct constructors. Fixes https://github.com/dotnet/roslyn/issues/55547 Feels too easy, probably missing something ¯\\\_(ツ)_/¯
./src/Compilers/Core/AnalyzerDriver/AnalyzerExceptionDescriptionBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class AnalyzerExceptionDescriptionBuilder { // Description separator private static readonly string s_separator = Environment.NewLine + "-----" + Environment.NewLine; public static string CreateDiagnosticDescription(this Exception exception) { if (exception is AggregateException aggregateException) { var flattened = aggregateException.Flatten(); return string.Join(s_separator, flattened.InnerExceptions.Select(e => GetExceptionMessage(e))); } if (exception != null) { return string.Join(s_separator, GetExceptionMessage(exception), CreateDiagnosticDescription(exception.InnerException)); } return string.Empty; } private static string GetExceptionMessage(Exception exception) { var fusionLog = (exception as FileNotFoundException)?.FusionLog; if (fusionLog == null) { return exception.ToString(); } return string.Join(s_separator, exception.Message, fusionLog); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class AnalyzerExceptionDescriptionBuilder { // Description separator private static readonly string s_separator = Environment.NewLine + "-----" + Environment.NewLine; public static string CreateDiagnosticDescription(this Exception exception) { if (exception is AggregateException aggregateException) { var flattened = aggregateException.Flatten(); return string.Join(s_separator, flattened.InnerExceptions.Select(e => GetExceptionMessage(e))); } if (exception != null) { return string.Join(s_separator, GetExceptionMessage(exception), CreateDiagnosticDescription(exception.InnerException)); } return string.Empty; } private static string GetExceptionMessage(Exception exception) { var fusionLog = (exception as FileNotFoundException)?.FusionLog; if (fusionLog == null) { return exception.ToString(); } return string.Join(s_separator, exception.Message, fusionLog); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/DriverStateTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // CONSIDER: when the compilation is the same as previous, the syntax trees must also be the same. // if we have a previous state table for a node, we can just short circuit knowing that it is up to date var compilationIsCached = GetLatestStateTableForNode(SharedInputNodes.Compilation).IsCached; // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { if (compilationIsCached && _previousTable._tables.TryGetValue(node, out var previousStateTable)) { _tableBuilder.Add(node, previousStateTable); } else { builders.Add(node.GetBuilder(_previousTable)); } } if (builders.Count == 0) { // bring over the previously cached syntax tree inputs _tableBuilder[SharedInputNodes.SyntaxTrees] = _previousTable._tables[SharedInputNodes.SyntaxTrees]; } else { // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = tree.GetRoot(_cancellationToken); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // CONSIDER: when the compilation is the same as previous, the syntax trees must also be the same. // if we have a previous state table for a node, we can just short circuit knowing that it is up to date var compilationIsCached = GetLatestStateTableForNode(SharedInputNodes.Compilation).IsCached; // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { if (compilationIsCached && _previousTable._tables.TryGetValue(node, out var previousStateTable)) { _tableBuilder.Add(node, previousStateTable); } else { builders.Add(node.GetBuilder(_previousTable)); } } if (builders.Count == 0) { // bring over the previously cached syntax tree inputs _tableBuilder[SharedInputNodes.SyntaxTrees] = _previousTable._tables[SharedInputNodes.SyntaxTrees]; } else { // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = new Lazy<SyntaxNode>(() => tree.GetRoot(_cancellationToken)); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/ISyntaxInputNode.cs
// Licensed to the .NET Foundation under one or more 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.Collections; namespace Microsoft.CodeAnalysis { internal interface ISyntaxInputNode { ISyntaxInputBuilder GetBuilder(DriverStateTable table); } internal interface ISyntaxInputBuilder { ISyntaxInputNode SyntaxInputNode { get; } void VisitTree(SyntaxNode root, EntryState state, SemanticModel? model, CancellationToken cancellationToken); void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables); } }
// Licensed to the .NET Foundation under one or more 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.Collections; namespace Microsoft.CodeAnalysis { internal interface ISyntaxInputNode { ISyntaxInputBuilder GetBuilder(DriverStateTable table); } internal interface ISyntaxInputBuilder { ISyntaxInputNode SyntaxInputNode { get; } void VisitTree(Lazy<SyntaxNode> root, EntryState state, SemanticModel? model, CancellationToken cancellationToken); void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables); } }
1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxInputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxInputNode<T> : IIncrementalGeneratorNode<T>, ISyntaxInputNode { private readonly Func<GeneratorSyntaxContext, CancellationToken, T> _transformFunc; private readonly Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> _registerOutputAndNode; private readonly Func<SyntaxNode, CancellationToken, bool> _filterFunc; private readonly IEqualityComparer<T> _comparer; private readonly object _filterKey = new object(); internal SyntaxInputNode(Func<SyntaxNode, CancellationToken, bool> filterFunc, Func<GeneratorSyntaxContext, CancellationToken, T> transformFunc, Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> registerOutputAndNode, IEqualityComparer<T>? comparer = null) { _transformFunc = transformFunc; _registerOutputAndNode = registerOutputAndNode; _filterFunc = filterFunc; _comparer = comparer ?? EqualityComparer<T>.Default; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<T>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new SyntaxInputNode<T>(_filterFunc, _transformFunc, _registerOutputAndNode, comparer); public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutputAndNode(this, output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxInputNode<T> _owner; private readonly NodeStateTable<SyntaxNode>.Builder _filterTable; private readonly NodeStateTable<T>.Builder _transformTable; public Builder(SyntaxInputNode<T> owner, DriverStateTable table) { _owner = owner; _filterTable = table.GetStateTableOrEmpty<SyntaxNode>(_owner._filterKey).ToBuilder(); _transformTable = table.GetStateTableOrEmpty<T>(_owner).ToBuilder(); } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { tables[_owner._filterKey] = _filterTable.ToImmutableAndFree(); tables[_owner] = _transformTable.ToImmutableAndFree(); } public void VisitTree(SyntaxNode root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (state == EntryState.Removed) { // mark both syntax *and* transform nodes removed _filterTable.RemoveEntries(); _transformTable.RemoveEntries(); } else { Debug.Assert(model is object); // get the syntax nodes from cache, or a syntax walk using the filter ImmutableArray<SyntaxNode> nodes; if (state != EntryState.Cached || !_filterTable.TryUseCachedEntries(out nodes)) { nodes = IncrementalGeneratorSyntaxWalker.GetFilteredNodes(root, _owner._filterFunc, cancellationToken); _filterTable.AddEntries(nodes, EntryState.Added); } // now, using the obtained syntax nodes, run the transform foreach (var node in nodes) { var value = new GeneratorSyntaxContext(node, model); var transformed = _owner._transformFunc(value, cancellationToken); if (state == EntryState.Added || !_transformTable.TryModifyEntry(transformed, _owner._comparer)) { _transformTable.AddEntry(transformed, EntryState.Added); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxInputNode<T> : IIncrementalGeneratorNode<T>, ISyntaxInputNode { private readonly Func<GeneratorSyntaxContext, CancellationToken, T> _transformFunc; private readonly Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> _registerOutputAndNode; private readonly Func<SyntaxNode, CancellationToken, bool> _filterFunc; private readonly IEqualityComparer<T> _comparer; private readonly object _filterKey = new object(); internal SyntaxInputNode(Func<SyntaxNode, CancellationToken, bool> filterFunc, Func<GeneratorSyntaxContext, CancellationToken, T> transformFunc, Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> registerOutputAndNode, IEqualityComparer<T>? comparer = null) { _transformFunc = transformFunc; _registerOutputAndNode = registerOutputAndNode; _filterFunc = filterFunc; _comparer = comparer ?? EqualityComparer<T>.Default; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<T>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new SyntaxInputNode<T>(_filterFunc, _transformFunc, _registerOutputAndNode, comparer); public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutputAndNode(this, output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxInputNode<T> _owner; private readonly NodeStateTable<SyntaxNode>.Builder _filterTable; private readonly NodeStateTable<T>.Builder _transformTable; public Builder(SyntaxInputNode<T> owner, DriverStateTable table) { _owner = owner; _filterTable = table.GetStateTableOrEmpty<SyntaxNode>(_owner._filterKey).ToBuilder(); _transformTable = table.GetStateTableOrEmpty<T>(_owner).ToBuilder(); } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { tables[_owner._filterKey] = _filterTable.ToImmutableAndFree(); tables[_owner] = _transformTable.ToImmutableAndFree(); } public void VisitTree(Lazy<SyntaxNode> root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (state == EntryState.Removed) { // mark both syntax *and* transform nodes removed _filterTable.RemoveEntries(); _transformTable.RemoveEntries(); } else { Debug.Assert(model is object); // get the syntax nodes from cache, or a syntax walk using the filter ImmutableArray<SyntaxNode> nodes; if (state != EntryState.Cached || !_filterTable.TryUseCachedEntries(out nodes)) { nodes = IncrementalGeneratorSyntaxWalker.GetFilteredNodes(root.Value, _owner._filterFunc, cancellationToken); _filterTable.AddEntries(nodes, EntryState.Added); } // now, using the obtained syntax nodes, run the transform foreach (var node in nodes) { var value = new GeneratorSyntaxContext(node, model); var transformed = _owner._transformFunc(value, cancellationToken); if (state == EntryState.Added || !_transformTable.TryModifyEntry(transformed, _owner._comparer)) { _transformTable.AddEntry(transformed, EntryState.Added); } } } } } } }
1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxReceiverInputNode.cs
// Licensed to the .NET Foundation under one or more 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.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxReceiverInputNode : ISyntaxInputNode, IIncrementalGeneratorNode<ISyntaxContextReceiver?> { private readonly SyntaxContextReceiverCreator _receiverCreator; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; public SyntaxReceiverInputNode(SyntaxContextReceiverCreator receiverCreator, Action<IIncrementalGeneratorOutputNode> registerOutput) { _receiverCreator = receiverCreator; _registerOutput = registerOutput; } public NodeStateTable<ISyntaxContextReceiver?> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<ISyntaxContextReceiver?> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<ISyntaxContextReceiver?>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<ISyntaxContextReceiver?> WithComparer(IEqualityComparer<ISyntaxContextReceiver?> comparer) { // we don't expose this node to end users throw ExceptionUtilities.Unreachable; } public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxReceiverInputNode _owner; private readonly NodeStateTable<ISyntaxContextReceiver?>.Builder _nodeStateTable; private readonly ISyntaxContextReceiver? _receiver; private readonly GeneratorSyntaxWalker? _walker; public Builder(SyntaxReceiverInputNode owner, DriverStateTable driverStateTable) { _owner = owner; _nodeStateTable = driverStateTable.GetStateTableOrEmpty<ISyntaxContextReceiver?>(_owner).ToBuilder(); try { _receiver = owner._receiverCreator(); } catch (Exception e) { throw new UserFunctionException(e); } if (_receiver is object) { _walker = new GeneratorSyntaxWalker(_receiver); } } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { _nodeStateTable.AddEntry(_receiver, EntryState.Modified); tables[_owner] = _nodeStateTable.ToImmutableAndFree(); } public void VisitTree(SyntaxNode root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (_walker is object && state != EntryState.Removed) { Debug.Assert(model is object); try { _walker.VisitWithModel(model, root); } catch (Exception e) { throw new UserFunctionException(e); } } } } } }
// Licensed to the .NET Foundation under one or more 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.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxReceiverInputNode : ISyntaxInputNode, IIncrementalGeneratorNode<ISyntaxContextReceiver?> { private readonly SyntaxContextReceiverCreator _receiverCreator; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; public SyntaxReceiverInputNode(SyntaxContextReceiverCreator receiverCreator, Action<IIncrementalGeneratorOutputNode> registerOutput) { _receiverCreator = receiverCreator; _registerOutput = registerOutput; } public NodeStateTable<ISyntaxContextReceiver?> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<ISyntaxContextReceiver?> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<ISyntaxContextReceiver?>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<ISyntaxContextReceiver?> WithComparer(IEqualityComparer<ISyntaxContextReceiver?> comparer) { // we don't expose this node to end users throw ExceptionUtilities.Unreachable; } public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxReceiverInputNode _owner; private readonly NodeStateTable<ISyntaxContextReceiver?>.Builder _nodeStateTable; private readonly ISyntaxContextReceiver? _receiver; private readonly GeneratorSyntaxWalker? _walker; public Builder(SyntaxReceiverInputNode owner, DriverStateTable driverStateTable) { _owner = owner; _nodeStateTable = driverStateTable.GetStateTableOrEmpty<ISyntaxContextReceiver?>(_owner).ToBuilder(); try { _receiver = owner._receiverCreator(); } catch (Exception e) { throw new UserFunctionException(e); } if (_receiver is object) { _walker = new GeneratorSyntaxWalker(_receiver); } } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { _nodeStateTable.AddEntry(_receiver, EntryState.Modified); tables[_owner] = _nodeStateTable.ToImmutableAndFree(); } public void VisitTree(Lazy<SyntaxNode> root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (_walker is object && state != EntryState.Removed) { Debug.Assert(model is object); try { _walker.VisitWithModel(model, root.Value); } catch (Exception e) { throw new UserFunctionException(e); } } } } } }
1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/InternalUtilities/StreamExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; namespace Roslyn.Utilities { internal static class StreamExtensions { /// <summary> /// Attempts to read all of the requested bytes from the stream into the buffer /// </summary> /// <returns> /// The number of bytes read. Less than <paramref name="count" /> will /// only be returned if the end of stream is reached before all bytes can be read. /// </returns> /// <remarks> /// Unlike <see cref="Stream.Read(byte[], int, int)"/> it is not guaranteed that /// the stream position or the output buffer will be unchanged if an exception is /// returned. /// </remarks> public static int TryReadAll( this Stream stream, byte[] buffer, int offset, int count) { // The implementations for many streams, e.g. FileStream, allows 0 bytes to be // read and returns 0, but the documentation for Stream.Read states that 0 is // only returned when the end of the stream has been reached. Rather than deal // with this contradiction, let's just never pass a count of 0 bytes Debug.Assert(count > 0); int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < count; totalBytesRead += bytesRead) { // Note: Don't attempt to save state in-between calls to .Read as it would // require a possibly massive intermediate buffer array bytesRead = stream.Read(buffer, offset + totalBytesRead, count - totalBytesRead); if (bytesRead == 0) { break; } } return totalBytesRead; } /// <summary> /// Reads all bytes from the current position of the given stream to its end. /// </summary> public static byte[] ReadAllBytes(this Stream stream) { if (stream.CanSeek) { long length = stream.Length - stream.Position; if (length == 0) { return Array.Empty<byte>(); } var buffer = new byte[length]; int actualLength = TryReadAll(stream, buffer, 0, buffer.Length); Array.Resize(ref buffer, actualLength); return buffer; } var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; namespace Roslyn.Utilities { internal static class StreamExtensions { /// <summary> /// Attempts to read all of the requested bytes from the stream into the buffer /// </summary> /// <returns> /// The number of bytes read. Less than <paramref name="count" /> will /// only be returned if the end of stream is reached before all bytes can be read. /// </returns> /// <remarks> /// Unlike <see cref="Stream.Read(byte[], int, int)"/> it is not guaranteed that /// the stream position or the output buffer will be unchanged if an exception is /// returned. /// </remarks> public static int TryReadAll( this Stream stream, byte[] buffer, int offset, int count) { // The implementations for many streams, e.g. FileStream, allows 0 bytes to be // read and returns 0, but the documentation for Stream.Read states that 0 is // only returned when the end of the stream has been reached. Rather than deal // with this contradiction, let's just never pass a count of 0 bytes Debug.Assert(count > 0); int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < count; totalBytesRead += bytesRead) { // Note: Don't attempt to save state in-between calls to .Read as it would // require a possibly massive intermediate buffer array bytesRead = stream.Read(buffer, offset + totalBytesRead, count - totalBytesRead); if (bytesRead == 0) { break; } } return totalBytesRead; } /// <summary> /// Reads all bytes from the current position of the given stream to its end. /// </summary> public static byte[] ReadAllBytes(this Stream stream) { if (stream.CanSeek) { long length = stream.Length - stream.Position; if (length == 0) { return Array.Empty<byte>(); } var buffer = new byte[length]; int actualLength = TryReadAll(stream, buffer, 0, buffer.Length); Array.Resize(ref buffer, actualLength); return buffer; } var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/CSharp/Portable/Symbols/PublicModel/ParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ParameterSymbol : Symbol, IParameterSymbol { private readonly Symbols.ParameterSymbol _underlying; private ITypeSymbol _lazyType; public ParameterSymbol(Symbols.ParameterSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ITypeSymbol IParameterSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IParameterSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); ImmutableArray<CustomModifier> IParameterSymbol.CustomModifiers { get { return _underlying.TypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IParameterSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } IParameterSymbol IParameterSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } RefKind IParameterSymbol.RefKind => _underlying.RefKind; bool IParameterSymbol.IsDiscard => _underlying.IsDiscard; bool IParameterSymbol.IsParams => _underlying.IsParams; bool IParameterSymbol.IsOptional => _underlying.IsOptional; bool IParameterSymbol.IsThis => _underlying.IsThis; int IParameterSymbol.Ordinal => _underlying.Ordinal; bool IParameterSymbol.HasExplicitDefaultValue => _underlying.HasExplicitDefaultValue; object IParameterSymbol.ExplicitDefaultValue => _underlying.ExplicitDefaultValue; #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitParameter(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitParameter(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class ParameterSymbol : Symbol, IParameterSymbol { private readonly Symbols.ParameterSymbol _underlying; private ITypeSymbol _lazyType; public ParameterSymbol(Symbols.ParameterSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ITypeSymbol IParameterSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IParameterSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); ImmutableArray<CustomModifier> IParameterSymbol.CustomModifiers { get { return _underlying.TypeWithAnnotations.CustomModifiers; } } ImmutableArray<CustomModifier> IParameterSymbol.RefCustomModifiers { get { return _underlying.RefCustomModifiers; } } IParameterSymbol IParameterSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } RefKind IParameterSymbol.RefKind => _underlying.RefKind; bool IParameterSymbol.IsDiscard => _underlying.IsDiscard; bool IParameterSymbol.IsParams => _underlying.IsParams; bool IParameterSymbol.IsOptional => _underlying.IsOptional; bool IParameterSymbol.IsThis => _underlying.IsThis; int IParameterSymbol.Ordinal => _underlying.Ordinal; bool IParameterSymbol.HasExplicitDefaultValue => _underlying.HasExplicitDefaultValue; object IParameterSymbol.ExplicitDefaultValue => _underlying.ExplicitDefaultValue; #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitParameter(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitParameter(this); } #endregion } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/VisualStudio/Core/Def/Implementation/ProjectTelemetry/VisualStudioProjectTelemetryService.cs
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.ProjectTelemetry; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.Shell; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioProjectTelemetryService : ForegroundThreadAffinitizedObject, IProjectTelemetryListener, IEventListener<object>, IDisposable { private const string EventPrefix = "VS/Compilers/Compilation/"; private const string PropertyPrefix = "VS.Compilers.Compilation.Inputs."; private const string TelemetryEventPath = EventPrefix + "Inputs"; private const string TelemetryExceptionEventPath = EventPrefix + "TelemetryUnhandledException"; private const string TelemetryProjectIdName = PropertyPrefix + "ProjectId"; private const string TelemetryProjectGuidName = PropertyPrefix + "ProjectGuid"; private const string TelemetryLanguageName = PropertyPrefix + "Language"; private const string TelemetryAnalyzerReferencesCountName = PropertyPrefix + "AnalyzerReferences.Count"; private const string TelemetryProjectReferencesCountName = PropertyPrefix + "ProjectReferences.Count"; private const string TelemetryMetadataReferencesCountName = PropertyPrefix + "MetadataReferences.Count"; private const string TelemetryDocumentsCountName = PropertyPrefix + "Documents.Count"; private const string TelemetryAdditionalDocumentsCountName = PropertyPrefix + "AdditionalDocuments.Count"; private readonly VisualStudioWorkspaceImpl _workspace; /// <summary> /// Our connection to the remote OOP server. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteProjectTelemetryService>? _lazyConnection; /// <summary> /// Queue where we enqueue the information we get from OOP to process in batch in the future. /// </summary> private readonly AsyncBatchingWorkQueue<ProjectTelemetryData>? _workQueue; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioProjectTelemetryService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider) : base(threadingContext) { _workspace = workspace; _workQueue = new AsyncBatchingWorkQueue<ProjectTelemetryData>( TimeSpan.FromSeconds(1), NotifyTelemetryServiceAsync, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.Telemetry), threadingContext.DisposalToken); } public void Dispose() { _lazyConnection?.Dispose(); } void IEventListener<object>.StartListening(Workspace workspace, object _) { if (workspace is VisualStudioWorkspace) _ = StartAsync(); } private async Task StartAsync() { // Have to catch all exceptions coming through here as this is called from a // fire-and-forget method and we want to make sure nothing leaks out. try { await StartWorkerAsync().ConfigureAwait(false); } catch (OperationCanceledException) { // Cancellation is normal (during VS closing). Just ignore. } catch (Exception e) when (FatalError.ReportAndCatch(e)) { // Otherwise report a watson for any other exception. Don't bring down VS. This is // a BG service we don't want impacting the user experience. } } private async Task StartWorkerAsync() { var cancellationToken = ThreadingContext.DisposalToken; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) return; // Pass ourselves in as the callback target for the OOP service. As it discovers // designer attributes it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteProjectTelemetryService>(callbackTarget: this); // Now kick off scanning in the OOP process. // If the call fails an error has already been reported and there is nothing more to do. _ = await _lazyConnection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.ComputeProjectTelemetryAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } private async ValueTask NotifyTelemetryServiceAsync( ImmutableArray<ProjectTelemetryData> infos, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<ProjectTelemetryData>.GetInstance(out var filteredInfos); AddFilteredData(infos, filteredInfos); using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var info in filteredInfos) tasks.Add(Task.Run(() => NotifyTelemetryService(info), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); } private void AddFilteredData(ImmutableArray<ProjectTelemetryData> infos, ArrayBuilder<ProjectTelemetryData> filteredInfos) { using var _ = PooledHashSet<ProjectId>.GetInstance(out var seenProjectIds); // Walk the list of telemetry items in reverse, and skip any items for a project once // we've already seen it once. That way, we're only reporting the most up to date // information for a project, and we're skipping the stale information. for (var i = infos.Length - 1; i >= 0; i--) { var info = infos[i]; if (seenProjectIds.Add(info.ProjectId)) filteredInfos.Add(info); } } private void NotifyTelemetryService(ProjectTelemetryData info) { try { var telemetryEvent = TelemetryHelper.TelemetryService.CreateEvent(TelemetryEventPath); telemetryEvent.SetStringProperty(TelemetryProjectIdName, info.ProjectId.Id.ToString()); telemetryEvent.SetStringProperty(TelemetryProjectGuidName, Guid.Empty.ToString()); telemetryEvent.SetStringProperty(TelemetryLanguageName, info.Language); telemetryEvent.SetIntProperty(TelemetryAnalyzerReferencesCountName, info.AnalyzerReferencesCount); telemetryEvent.SetIntProperty(TelemetryProjectReferencesCountName, info.ProjectReferencesCount); telemetryEvent.SetIntProperty(TelemetryMetadataReferencesCountName, info.MetadataReferencesCount); telemetryEvent.SetIntProperty(TelemetryDocumentsCountName, info.DocumentsCount); telemetryEvent.SetIntProperty(TelemetryAdditionalDocumentsCountName, info.AdditionalDocumentsCount); TelemetryHelper.DefaultTelemetrySession.PostEvent(telemetryEvent); } catch (Exception e) { // The telemetry service itself can throw. // So, to be very careful, put this in a try/catch too. try { var exceptionEvent = TelemetryHelper.TelemetryService.CreateEvent(TelemetryExceptionEventPath); exceptionEvent.SetStringProperty("Type", e.GetTypeDisplayName()); exceptionEvent.SetStringProperty("Message", e.Message); exceptionEvent.SetStringProperty("StackTrace", e.StackTrace); TelemetryHelper.DefaultTelemetrySession.PostEvent(exceptionEvent); } catch { } } } /// <summary> /// Callback from the OOP service back into us. /// </summary> public ValueTask ReportProjectTelemetryDataAsync(ProjectTelemetryData info, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workQueue); _workQueue.AddWork(info); return ValueTaskFactory.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. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.ProjectTelemetry; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.Shell; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioProjectTelemetryService : ForegroundThreadAffinitizedObject, IProjectTelemetryListener, IEventListener<object>, IDisposable { private const string EventPrefix = "VS/Compilers/Compilation/"; private const string PropertyPrefix = "VS.Compilers.Compilation.Inputs."; private const string TelemetryEventPath = EventPrefix + "Inputs"; private const string TelemetryExceptionEventPath = EventPrefix + "TelemetryUnhandledException"; private const string TelemetryProjectIdName = PropertyPrefix + "ProjectId"; private const string TelemetryProjectGuidName = PropertyPrefix + "ProjectGuid"; private const string TelemetryLanguageName = PropertyPrefix + "Language"; private const string TelemetryAnalyzerReferencesCountName = PropertyPrefix + "AnalyzerReferences.Count"; private const string TelemetryProjectReferencesCountName = PropertyPrefix + "ProjectReferences.Count"; private const string TelemetryMetadataReferencesCountName = PropertyPrefix + "MetadataReferences.Count"; private const string TelemetryDocumentsCountName = PropertyPrefix + "Documents.Count"; private const string TelemetryAdditionalDocumentsCountName = PropertyPrefix + "AdditionalDocuments.Count"; private readonly VisualStudioWorkspaceImpl _workspace; /// <summary> /// Our connection to the remote OOP server. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteProjectTelemetryService>? _lazyConnection; /// <summary> /// Queue where we enqueue the information we get from OOP to process in batch in the future. /// </summary> private readonly AsyncBatchingWorkQueue<ProjectTelemetryData>? _workQueue; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioProjectTelemetryService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider) : base(threadingContext) { _workspace = workspace; _workQueue = new AsyncBatchingWorkQueue<ProjectTelemetryData>( TimeSpan.FromSeconds(1), NotifyTelemetryServiceAsync, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.Telemetry), threadingContext.DisposalToken); } public void Dispose() { _lazyConnection?.Dispose(); } void IEventListener<object>.StartListening(Workspace workspace, object _) { if (workspace is VisualStudioWorkspace) _ = StartAsync(); } private async Task StartAsync() { // Have to catch all exceptions coming through here as this is called from a // fire-and-forget method and we want to make sure nothing leaks out. try { await StartWorkerAsync().ConfigureAwait(false); } catch (OperationCanceledException) { // Cancellation is normal (during VS closing). Just ignore. } catch (Exception e) when (FatalError.ReportAndCatch(e)) { // Otherwise report a watson for any other exception. Don't bring down VS. This is // a BG service we don't want impacting the user experience. } } private async Task StartWorkerAsync() { var cancellationToken = ThreadingContext.DisposalToken; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) return; // Pass ourselves in as the callback target for the OOP service. As it discovers // designer attributes it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteProjectTelemetryService>(callbackTarget: this); // Now kick off scanning in the OOP process. // If the call fails an error has already been reported and there is nothing more to do. _ = await _lazyConnection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.ComputeProjectTelemetryAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } private async ValueTask NotifyTelemetryServiceAsync( ImmutableArray<ProjectTelemetryData> infos, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<ProjectTelemetryData>.GetInstance(out var filteredInfos); AddFilteredData(infos, filteredInfos); using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var info in filteredInfos) tasks.Add(Task.Run(() => NotifyTelemetryService(info), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); } private void AddFilteredData(ImmutableArray<ProjectTelemetryData> infos, ArrayBuilder<ProjectTelemetryData> filteredInfos) { using var _ = PooledHashSet<ProjectId>.GetInstance(out var seenProjectIds); // Walk the list of telemetry items in reverse, and skip any items for a project once // we've already seen it once. That way, we're only reporting the most up to date // information for a project, and we're skipping the stale information. for (var i = infos.Length - 1; i >= 0; i--) { var info = infos[i]; if (seenProjectIds.Add(info.ProjectId)) filteredInfos.Add(info); } } private void NotifyTelemetryService(ProjectTelemetryData info) { try { var telemetryEvent = TelemetryHelper.TelemetryService.CreateEvent(TelemetryEventPath); telemetryEvent.SetStringProperty(TelemetryProjectIdName, info.ProjectId.Id.ToString()); telemetryEvent.SetStringProperty(TelemetryProjectGuidName, Guid.Empty.ToString()); telemetryEvent.SetStringProperty(TelemetryLanguageName, info.Language); telemetryEvent.SetIntProperty(TelemetryAnalyzerReferencesCountName, info.AnalyzerReferencesCount); telemetryEvent.SetIntProperty(TelemetryProjectReferencesCountName, info.ProjectReferencesCount); telemetryEvent.SetIntProperty(TelemetryMetadataReferencesCountName, info.MetadataReferencesCount); telemetryEvent.SetIntProperty(TelemetryDocumentsCountName, info.DocumentsCount); telemetryEvent.SetIntProperty(TelemetryAdditionalDocumentsCountName, info.AdditionalDocumentsCount); TelemetryHelper.DefaultTelemetrySession.PostEvent(telemetryEvent); } catch (Exception e) { // The telemetry service itself can throw. // So, to be very careful, put this in a try/catch too. try { var exceptionEvent = TelemetryHelper.TelemetryService.CreateEvent(TelemetryExceptionEventPath); exceptionEvent.SetStringProperty("Type", e.GetTypeDisplayName()); exceptionEvent.SetStringProperty("Message", e.Message); exceptionEvent.SetStringProperty("StackTrace", e.StackTrace); TelemetryHelper.DefaultTelemetrySession.PostEvent(exceptionEvent); } catch { } } } /// <summary> /// Callback from the OOP service back into us. /// </summary> public ValueTask ReportProjectTelemetryDataAsync(ProjectTelemetryData info, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workQueue); _workQueue.AddWork(info); return ValueTaskFactory.CompletedTask; } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyCompilationsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { // Add member N3.CGoo GetClass(); } namespace N3 { public class CGoo { public struct SGoo { // Update member public enum EGoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01"); var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01"); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind); Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] [WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] public void ExtendedPartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { public partial void M() { } public partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None)); } [Fact] public void RecursiveReferenceToConstructedGeneric() { var src1 = @"using System.Collections.Generic; class C { public void M<Z>(List<Z> list) { var v = list.Add(default(Z)); } }"; var comp1 = CreateCompilation(src1); var comp2 = CreateCompilation(src1); var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList(); var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList(); // First, make sure that all the symbols in this file resolve properly // to themselves. ResolveAndVerifySymbolList(symbols1, symbols2, comp1); // Now do this for the members of types we see. We want this // so we hit things like the members of the constructed type // List<Z> var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); ResolveAndVerifySymbolList(members1, members2, comp1); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DGoo(int p1); namespace N1.N2 { public interface IBase { } public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IGoo : IBase // add base interface { } namespace N3 { public class CGoo : IGoo // impl interface { private struct SGoo // change modifier { internal enum EGoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None); ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None)); } [WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules.First(); sym2 = comp2.Assembly.Modules.First(); ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules.First(); var module2 = compilation2.Assembly.Modules.First(); // different AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None)); AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true); var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { // Add member N3.CGoo GetClass(); } namespace N3 { public class CGoo { public struct SGoo { // Update member public enum EGoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01"); var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01"); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind); Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] [WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] public void ExtendedPartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { public partial void M() { } public partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None)); } [Fact] public void RecursiveReferenceToConstructedGeneric() { var src1 = @"using System.Collections.Generic; class C { public void M<Z>(List<Z> list) { var v = list.Add(default(Z)); } }"; var comp1 = CreateCompilation(src1); var comp2 = CreateCompilation(src1); var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList(); var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList(); // First, make sure that all the symbols in this file resolve properly // to themselves. ResolveAndVerifySymbolList(symbols1, symbols2, comp1); // Now do this for the members of types we see. We want this // so we hit things like the members of the constructed type // List<Z> var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); ResolveAndVerifySymbolList(members1, members2, comp1); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DGoo(int p1); namespace N1.N2 { public interface IBase { } public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IGoo : IBase // add base interface { } namespace N3 { public class CGoo : IGoo // impl interface { private struct SGoo // change modifier { internal enum EGoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None); ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None)); } [WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules.First(); sym2 = comp2.Assembly.Modules.First(); ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules.First(); var module2 = compilation2.Assembly.Modules.First(); // different AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None)); AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true); var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #endregion } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/CSharpTest2/Recommendations/AbstractKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AbstractKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticInInterface() { await VerifyKeywordAsync(@"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { abstract $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { virtual $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOverride() { await VerifyKeywordAsync( @"class C { override $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AbstractKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticInInterface() { await VerifyKeywordAsync(@"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { abstract $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { virtual $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind) { await VerifyAbsenceAsync(declarationKind + @" C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOverride() { await VerifyKeywordAsync( @"class C { override $$"); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Enumerator`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerator<T> : Enumerator, IEnumerator<T> { public static new readonly IEnumerator<T> Instance = new Enumerator<T>(); protected Enumerator() { } public new T Current => throw new InvalidOperationException(); public void Dispose() { } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerator<T> : Enumerator, IEnumerator<T> { public static new readonly IEnumerator<T> Instance = new Enumerator<T>(); protected Enumerator() { } public new T Current => throw new InvalidOperationException(); public void Dispose() { } } } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Core.Wpf/IWpfTextViewExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IWpfTextViewExtensions { public static void SizeToFit(this IWpfTextView view, IThreadingContext threadingContext) { void firstLayout(object sender, TextViewLayoutChangedEventArgs args) { threadingContext.JoinableTaskFactory.RunAsync(async () => { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); var newHeight = view.LineHeight * view.TextBuffer.CurrentSnapshot.LineCount; if (IsGreater(newHeight, view.VisualElement.Height)) { view.VisualElement.Height = newHeight; } var newWidth = view.MaxTextRightCoordinate; if (IsGreater(newWidth, view.VisualElement.Width)) { view.VisualElement.Width = newWidth; } }); view.LayoutChanged -= firstLayout; } view.LayoutChanged += firstLayout; static bool IsGreater(double value, double other) => IsNormal(value) && (!IsNormal(other) || value > other); static bool IsNormal(double value) => !double.IsNaN(value) && !double.IsInfinity(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. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IWpfTextViewExtensions { public static void SizeToFit(this IWpfTextView view, IThreadingContext threadingContext) { void firstLayout(object sender, TextViewLayoutChangedEventArgs args) { threadingContext.JoinableTaskFactory.RunAsync(async () => { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); var newHeight = view.LineHeight * view.TextBuffer.CurrentSnapshot.LineCount; if (IsGreater(newHeight, view.VisualElement.Height)) { view.VisualElement.Height = newHeight; } var newWidth = view.MaxTextRightCoordinate; if (IsGreater(newWidth, view.VisualElement.Width)) { view.VisualElement.Width = newWidth; } }); view.LayoutChanged -= firstLayout; } view.LayoutChanged += firstLayout; static bool IsGreater(double value, double other) => IsNormal(value) && (!IsNormal(other) || value > other); static bool IsNormal(double value) => !double.IsNaN(value) && !double.IsInfinity(value); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionValidator.Validator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator { public static bool Check(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => node switch { ExpressionSyntax expression => CheckExpression(semanticModel, expression, cancellationToken), BlockSyntax block => CheckBlock(block), StatementSyntax statement => CheckStatement(statement), GlobalStatementSyntax _ => CheckGlobalStatement(), _ => false, }; private static bool CheckGlobalStatement() => true; private static bool CheckBlock(BlockSyntax block) { // TODO(cyrusn): Is it intentional that fixed statement is not in this list? return block.Parent is BlockSyntax || block.Parent is DoStatementSyntax || block.Parent is ElseClauseSyntax || block.Parent is CommonForEachStatementSyntax || block.Parent is ForStatementSyntax || block.Parent is IfStatementSyntax || block.Parent is LockStatementSyntax || block.Parent is UsingStatementSyntax || block.Parent is WhileStatementSyntax; } private static bool CheckExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO(cyrusn): This is probably unnecessary. What we should be doing is binding // the type of the expression and seeing if it contains an anonymous type. if (expression is AnonymousObjectCreationExpressionSyntax) { return false; } return expression.CanReplaceWithRValue(semanticModel, cancellationToken); } private static bool CheckStatement(StatementSyntax statement) => statement is CheckedStatementSyntax || statement is DoStatementSyntax || statement is EmptyStatementSyntax || statement is ExpressionStatementSyntax || statement is FixedStatementSyntax || statement is CommonForEachStatementSyntax || statement is ForStatementSyntax || statement is IfStatementSyntax || statement is LocalDeclarationStatementSyntax || statement is LockStatementSyntax || statement is ReturnStatementSyntax || statement is SwitchStatementSyntax || statement is ThrowStatementSyntax || statement is TryStatementSyntax || statement is UnsafeStatementSyntax || statement is UsingStatementSyntax || statement is WhileStatementSyntax; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator { public static bool Check(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => node switch { ExpressionSyntax expression => CheckExpression(semanticModel, expression, cancellationToken), BlockSyntax block => CheckBlock(block), StatementSyntax statement => CheckStatement(statement), GlobalStatementSyntax _ => CheckGlobalStatement(), _ => false, }; private static bool CheckGlobalStatement() => true; private static bool CheckBlock(BlockSyntax block) { // TODO(cyrusn): Is it intentional that fixed statement is not in this list? return block.Parent is BlockSyntax || block.Parent is DoStatementSyntax || block.Parent is ElseClauseSyntax || block.Parent is CommonForEachStatementSyntax || block.Parent is ForStatementSyntax || block.Parent is IfStatementSyntax || block.Parent is LockStatementSyntax || block.Parent is UsingStatementSyntax || block.Parent is WhileStatementSyntax; } private static bool CheckExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO(cyrusn): This is probably unnecessary. What we should be doing is binding // the type of the expression and seeing if it contains an anonymous type. if (expression is AnonymousObjectCreationExpressionSyntax) { return false; } return expression.CanReplaceWithRValue(semanticModel, cancellationToken); } private static bool CheckStatement(StatementSyntax statement) => statement is CheckedStatementSyntax || statement is DoStatementSyntax || statement is EmptyStatementSyntax || statement is ExpressionStatementSyntax || statement is FixedStatementSyntax || statement is CommonForEachStatementSyntax || statement is ForStatementSyntax || statement is IfStatementSyntax || statement is LocalDeclarationStatementSyntax || statement is LockStatementSyntax || statement is ReturnStatementSyntax || statement is SwitchStatementSyntax || statement is ThrowStatementSyntax || statement is TryStatementSyntax || statement is UnsafeStatementSyntax || statement is UsingStatementSyntax || statement is WhileStatementSyntax; } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Server/VBCSCompiler/MemoryHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Uses p/invoke to gain access to information about how much memory this process is using /// and how much is still available. /// </summary> [StructLayout(LayoutKind.Sequential)] internal sealed class MemoryHelper { private MemoryHelper() { this.Length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. public int Length; public int PercentPhysicalUsed; public ulong MaxPhysical; public ulong AvailablePhysical; public ulong MaxPageFile; public ulong AvailablePageFile; public ulong MaxVirtual; public ulong AvailableVirtual; public ulong Reserved; //always 0 public static bool IsMemoryAvailable(ICompilerServerLogger logger) { if (!PlatformInformation.IsWindows) { // assume we have enough memory on non-Windows machines return true; } MemoryHelper status = new MemoryHelper(); GlobalMemoryStatusEx(status); ulong max = status.MaxVirtual; ulong free = status.AvailableVirtual; int shift = 20; string unit = "MB"; if (free >> shift == 0) { shift = 10; unit = "KB"; } logger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); return free >= 800 << 20; // Value (500MB) is arbitrary; feel free to improve. } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalMemoryStatusEx([In, Out] MemoryHelper buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// Uses p/invoke to gain access to information about how much memory this process is using /// and how much is still available. /// </summary> [StructLayout(LayoutKind.Sequential)] internal sealed class MemoryHelper { private MemoryHelper() { this.Length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. public int Length; public int PercentPhysicalUsed; public ulong MaxPhysical; public ulong AvailablePhysical; public ulong MaxPageFile; public ulong AvailablePageFile; public ulong MaxVirtual; public ulong AvailableVirtual; public ulong Reserved; //always 0 public static bool IsMemoryAvailable(ICompilerServerLogger logger) { if (!PlatformInformation.IsWindows) { // assume we have enough memory on non-Windows machines return true; } MemoryHelper status = new MemoryHelper(); GlobalMemoryStatusEx(status); ulong max = status.MaxVirtual; ulong free = status.AvailableVirtual; int shift = 20; string unit = "MB"; if (free >> shift == 0) { shift = 10; unit = "KB"; } logger.Log("Free memory: {1}{0} of {2}{0}.", unit, free >> shift, max >> shift); return free >= 800 << 20; // Value (500MB) is arbitrary; feel free to improve. } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalMemoryStatusEx([In, Out] MemoryHelper buffer); } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/InternalImplementationOnlyAttribute.cs
// Licensed to the .NET Foundation under one or more 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 System.Runtime.CompilerServices { /// <summary> /// This is a marker attribute that can be put on an interface to denote that only internal implementations /// of that interface should exist. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] internal sealed class InternalImplementationOnlyAttribute : Attribute { } }
// Licensed to the .NET Foundation under one or more 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 System.Runtime.CompilerServices { /// <summary> /// This is a marker attribute that can be put on an interface to denote that only internal implementations /// of that interface should exist. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] internal sealed class InternalImplementationOnlyAttribute : Attribute { } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Test/EditorAdapter/SpanExtensionsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter { public class SpanExtensionsTest { [Fact] public void ConvertToTextSpan() { static void del(int start, int length) { var span = new Span(start, length); var textSpan = span.ToTextSpan(); Assert.Equal(start, textSpan.Start); Assert.Equal(length, textSpan.Length); } del(0, 5); del(10, 15); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter { public class SpanExtensionsTest { [Fact] public void ConvertToTextSpan() { static void del(int start, int length) { var span = new Span(start, length); var textSpan = span.ToTextSpan(); Assert.Equal(start, textSpan.Start); Assert.Equal(length, textSpan.Length); } del(0, 5); del(10, 15); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Core.Wpf/Diagnostics/UnnecessaryCodeFormatDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Diagnostics { [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.UnnecessaryCode)] [Name(ClassificationTypeDefinitions.UnnecessaryCode)] [Order(After = Priority.High)] [UserVisible(false)] internal sealed class UnnecessaryCodeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnnecessaryCodeFormatDefinition() { this.DisplayName = EditorFeaturesResources.Unnecessary_Code; this.ForegroundOpacity = 0.6; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Diagnostics { [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.UnnecessaryCode)] [Name(ClassificationTypeDefinitions.UnnecessaryCode)] [Order(After = Priority.High)] [UserVisible(false)] internal sealed class UnnecessaryCodeFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnnecessaryCodeFormatDefinition() { this.DisplayName = EditorFeaturesResources.Unnecessary_Code; this.ForegroundOpacity = 0.6; } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/Core/Portable/Completion/MatchPriority.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Completion { /// <summary> /// An additional hint to the matching algorithm that can /// augment or override the existing text-based matching. /// </summary> public static class MatchPriority { /// <summary> /// The matching algorithm should give this item no special treatment. /// /// Ordinary <see cref="CompletionProvider"/>s typically specify this. /// </summary> public static readonly int Default = 0; /// <summary> /// The matching algorithm will tend to prefer this item unless /// a dramatically better text-based match is available. /// /// With no filter text, this item (or the first item alphabetically /// with this priority) should always be selected. /// /// This is used for specific IDE scenarios like "Object creation preselection" /// or "Enum preselection" or "Completion list tag preselection". /// </summary> public static readonly int Preselect = int.MaxValue / 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. #nullable disable namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// An additional hint to the matching algorithm that can /// augment or override the existing text-based matching. /// </summary> public static class MatchPriority { /// <summary> /// The matching algorithm should give this item no special treatment. /// /// Ordinary <see cref="CompletionProvider"/>s typically specify this. /// </summary> public static readonly int Default = 0; /// <summary> /// The matching algorithm will tend to prefer this item unless /// a dramatically better text-based match is available. /// /// With no filter text, this item (or the first item alphabetically /// with this priority) should always be selected. /// /// This is used for specific IDE scenarios like "Object creation preselection" /// or "Enum preselection" or "Completion list tag preselection". /// </summary> public static readonly int Preselect = int.MaxValue / 2; } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/Core/Portable/InheritanceMargin/IRemoteInheritanceMarginService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal interface IRemoteInheritanceMarginService { ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync( PinnedSolutionInfo pinnedSolutionInfo, ProjectId projectId, ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal interface IRemoteInheritanceMarginService { ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync( PinnedSolutionInfo pinnedSolutionInfo, ProjectId projectId, ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableDictionaryTestBase.nonnetstandard.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTestBase.nonnetstandard.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public void EnumeratorTest() { EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void KeysTest() { KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.True(IsSame(map, jointMap)); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.True(IsSame(map, jointMap)); jointMap = map2.AddRange(map.ToBuilder()); Assert.True(IsSame(map, jointMap)); } [Fact] public void AddDescendingTest() { AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { AddRemoveEnumerableTestHelper(Empty<int, int>()); } private static IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Assert.NotNull(map); Assert.NotNull(key); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); return addedMap; } protected static void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Assert.NotNull(map); for (int i = 0; i < 10; i++) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected static void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected static void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Assert.NotNull(map); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Assert.NotNull(empty); Assert.True(IsSame(empty, empty.RemoveRange(Enumerable.Empty<int>()))); Assert.True(IsSame(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()))); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); } protected static void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) where TKey : notnull { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected static void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue?>)nonEmpty).Values, default(TValue)); } protected static void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Equal(default(KeyValuePair<int, GenericParameterHelper>), manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Equal(default(KeyValuePair<int, GenericParameterHelper>), manualEnum.Current); } private static List<T> ToListNonGeneric<T>(IEnumerable sequence) { Assert.NotNull(sequence); var list = new List<T>(); var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { list.Add((T)enumerator.Current); } return list; } private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { if (collection is null) throw new ArgumentNullException(nameof(collection)); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T)!)); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); Assert.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null!, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTestBase.nonnetstandard.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public void EnumeratorTest() { EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void KeysTest() { KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.True(IsSame(map, jointMap)); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.True(IsSame(map, jointMap)); jointMap = map2.AddRange(map.ToBuilder()); Assert.True(IsSame(map, jointMap)); } [Fact] public void AddDescendingTest() { AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { AddRemoveEnumerableTestHelper(Empty<int, int>()); } private static IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Assert.NotNull(map); Assert.NotNull(key); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); return addedMap; } protected static void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Assert.NotNull(map); for (int i = 0; i < 10; i++) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected static void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected static void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Assert.NotNull(map); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Assert.NotNull(empty); Assert.True(IsSame(empty, empty.RemoveRange(Enumerable.Empty<int>()))); Assert.True(IsSame(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()))); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); } protected static void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) where TKey : notnull { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected static void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue?>)nonEmpty).Values, default(TValue)); } protected static void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Equal(default(KeyValuePair<int, GenericParameterHelper>), manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Equal(default(KeyValuePair<int, GenericParameterHelper>), manualEnum.Current); } private static List<T> ToListNonGeneric<T>(IEnumerable sequence) { Assert.NotNull(sequence); var list = new List<T>(); var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { list.Add((T)enumerator.Current); } return list; } private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { if (collection is null) throw new ArgumentNullException(nameof(collection)); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T)!)); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); Assert.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null!, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/CodeAnalysisTest/Text/TextChangeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { public class TextChangeTests { private readonly ITestOutputHelper _output; public TextChangeTests(ITestOutputHelper output) { _output = output; } [Fact] public void TestSubTextStart() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(6); Assert.Equal("World", subText.ToString()); } [Fact] public void TestSubTextSpanFirst() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(0, 5)); Assert.Equal("Hello", subText.ToString()); } [Fact] public void TestSubTextSpanLast() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(6, 5)); Assert.Equal("World", subText.ToString()); } [Fact] public void TestSubTextSpanMid() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(4, 3)); Assert.Equal("o W", subText.ToString()); } [Fact] public void TestChangedText() { var text = SourceText.From("Hello World"); var newText = text.Replace(6, 0, "Beautiful "); Assert.Equal("Hello Beautiful World", newText.ToString()); } [Fact] public void TestChangedTextChanges() { var text = SourceText.From("Hello World"); var newText = text.Replace(6, 0, "Beautiful "); var changes = newText.GetChangeRanges(text); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(6, changes[0].Span.Start); Assert.Equal(0, changes[0].Span.Length); Assert.Equal(10, changes[0].NewLength); } [Fact] public void TestChangedTextWithMultipleChanges() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(0, 5), "Halo"), new TextChange(new TextSpan(6, 5), "Universe")); Assert.Equal("Halo Universe", newText.ToString()); } [Fact] public void TestChangedTextWithMultipleOverlappingChanges() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(0, 5), "Halo"), new TextChange(new TextSpan(3, 5), "Universe") }; Assert.Throws<ArgumentException>(() => text.WithChanges(changes)); } [Fact] public void TestChangedTextWithMultipleUnorderedChanges() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 5), "Universe"), new TextChange(new TextSpan(0, 5), "Halo") }; var newText = text.WithChanges(changes); Assert.Equal("Halo Universe", newText.ToString()); } [Fact] public void TestChangedTextWithMultipleUnorderedChangesAndOneIsOutOfBounds() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 7), "Universe"), new TextChange(new TextSpan(0, 5), "Halo") }; Assert.ThrowsAny<ArgumentException>(() => { var newText = text.WithChanges(changes); }); } [Fact] public void TestChangedTextWithMultipleConsecutiveInsertsSamePosition() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 0), "Super "), new TextChange(new TextSpan(6, 0), "Spectacular ")); Assert.Equal("Hello Super Spectacular World", newText.ToString()); } [Fact] public void TestChangedTextWithReplaceAfterInsertSamePosition() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 0), "Super "), new TextChange(new TextSpan(6, 2), "Vu")); Assert.Equal("Hello Super Vurld", newText.ToString()); } [Fact] public void TestChangedTextWithReplaceBeforeInsertSamePosition() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 2), "Vu"), new TextChange(new TextSpan(6, 0), "Super ") }; var newText = text.WithChanges(changes); Assert.Equal("Hello Super Vurld", newText.ToString()); } [Fact] public void TestChangedTextWithDeleteAfterDeleteAdjacent() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty), new TextChange(new TextSpan(5, 1), string.Empty)); Assert.Equal("HellWorld", newText.ToString()); } [Fact] public void TestSubTextAfterMultipleChanges() { var text = SourceText.From("Hello World", Encoding.Unicode, SourceHashAlgorithm.Sha256); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty), new TextChange(new TextSpan(6, 5), "Universe")); var subText = newText.GetSubText(new TextSpan(3, 4)); Assert.Equal("l Un", subText.ToString()); Assert.Equal(SourceHashAlgorithm.Sha256, subText.ChecksumAlgorithm); Assert.Same(Encoding.Unicode, subText.Encoding); } [Fact] public void TestLinesInChangedText() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty)); Assert.Equal(1, newText.Lines.Count); } [Fact] public void TestCopyTo() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 5), "Universe")); var destination = new char[32]; newText.CopyTo(0, destination, 0, 0); //should copy nothing and not throw. Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(-1, destination, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, -1, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, 0, -1)); Assert.Throws<ArgumentNullException>(() => newText.CopyTo(0, null, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(newText.Length - 1, destination, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, destination.Length - 1, 2)); } [Fact] public void TestGetTextChangesToChangedText() { var text = SourceText.From(new string('.', 2048), Encoding.Unicode, SourceHashAlgorithm.Sha256); // start bigger than GetText() copy buffer var changes = new TextChange[] { new TextChange(new TextSpan(0, 1), "[1]"), new TextChange(new TextSpan(1, 1), "[2]"), new TextChange(new TextSpan(5, 0), "[3]"), new TextChange(new TextSpan(25, 2), "[4]") }; var newText = text.WithChanges(changes); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); Assert.Same(Encoding.Unicode, newText.Encoding); var result = newText.GetTextChanges(text).ToList(); Assert.Equal(changes.Length, result.Count); for (int i = 0; i < changes.Length; i++) { var expected = changes[i]; var actual = result[i]; Assert.Equal(expected.Span, actual.Span); Assert.Equal(expected.NewText, actual.NewText); } } private sealed class TextLineEqualityComparer : IEqualityComparer<TextLine> { public bool Equals(TextLine x, TextLine y) { return x.Span == y.Span; } public int GetHashCode(TextLine obj) { return obj.Span.GetHashCode(); } } private static void AssertChangedTextLinesHelper(string originalText, params TextChange[] changes) { var changedText = SourceText.From(originalText).WithChanges(changes); Assert.Equal(SourceText.From(changedText.ToString()).Lines, changedText.Lines, new TextLineEqualityComparer()); } [Fact] public void TestOptimizedSourceTextLinesSimpleSubstitution() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), "IN"), new TextChange(new TextSpan(15, 2), "IN")); } [Fact] public void TestOptimizedSourceTextLinesSubstitutionWithLongerText() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), new string('a', 10)), new TextChange(new TextSpan(15, 2), new string('a', 10))); } [Fact] public void TestOptimizedSourceTextLinesInsertCrLf() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), "\r\n"), new TextChange(new TextSpan(15, 2), "\r\n")); } [Fact] public void TestOptimizedSourceTextLinesSimpleCr() { AssertChangedTextLinesHelper("Line1\rLine2\rLine3", new TextChange(new TextSpan(6, 0), "aa\r"), new TextChange(new TextSpan(11, 0), "aa\r")); } [Fact] public void TestOptimizedSourceTextLinesSimpleLf() { AssertChangedTextLinesHelper("Line1\nLine2\nLine3", new TextChange(new TextSpan(6, 0), "aa\n"), new TextChange(new TextSpan(11, 0), "aa\n")); } [Fact] public void TestOptimizedSourceTextLinesRemoveCrLf() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(4, 4), "aaaaaa"), new TextChange(new TextSpan(15, 4), "aaaaaa")); } [Fact] public void TestOptimizedSourceTextLinesBrakeCrLf() { AssertChangedTextLinesHelper("Test\r\nMessage", new TextChange(new TextSpan(5, 0), "aaaaaa")); } [Fact] public void TestOptimizedSourceTextLinesBrakeCrLfWithLfPrefixedAndCrSuffixed() { AssertChangedTextLinesHelper("Test\r\nMessage", new TextChange(new TextSpan(5, 0), "\naaaaaa\r")); } [Fact] public void TestOptimizedSourceTextLineInsertAtEnd() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3\r\n", new TextChange(new TextSpan(21, 0), "Line4\r\n"), new TextChange(new TextSpan(21, 0), "Line5\r\n")); } [Fact] public void TestManySingleCharacterAdds() { var str = new String('.', 1024); var text = SourceText.From(str); var lines = text.Lines; int n = 20000; var expected = str; for (int i = 0; i < n; i++) { char c = (char)(((ushort)'a') + (i % 26)); text = text.Replace(50 + i, 0, c.ToString()); expected = expected.Substring(0, 50 + i) + c + expected.Substring(50 + i); } Assert.Equal(str.Length + n, text.Length); Assert.Equal(expected, text.ToString()); } [Fact] public void TestManySingleCharacterReplacements() { var str = new String('.', 1024); var text = SourceText.From(str); var lines = text.Lines; var expected = str; for (int i = 0; i < str.Length; i++) { char c = (char)(((ushort)'a') + (i % 26)); text = text.Replace(i, 1, c.ToString()); expected = expected.Substring(0, i) + c + str.Substring(i + 1); } Assert.Equal(str.Length, text.Length); Assert.Equal(expected, text.ToString()); } [Fact] public void TestSubTextCausesSizeLengthDifference() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(26, text.Length); Assert.Equal(26, text.StorageSize); var subtext = text.GetSubText(new TextSpan(5, 10)); Assert.Equal(10, subtext.Length); Assert.Equal("fghijklmno", subtext.ToString()); Assert.Equal(26, subtext.StorageSize); } [Fact] public void TestRemovingMajorityOfTextCompressesStorage() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); var newText = text.Replace(new TextSpan(0, 20), ""); Assert.Equal(6, newText.Length); Assert.Equal(6, newText.StorageSize); } [Fact] public void TestRemovingMinorityOfTextDoesNotCompressesStorage() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); var newText = text.Replace(new TextSpan(10, 6), ""); Assert.Equal(20, newText.Length); Assert.Equal(26, newText.StorageSize); } [Fact] public void TestRemovingTextCreatesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var newText = text.Replace(new TextSpan(10, 1), ""); Assert.Equal(25, newText.Length); Assert.Equal(26, newText.StorageSize); Assert.Equal(2, newText.Segments.Length); Assert.Equal("abcdefghij", newText.Segments[0].ToString()); Assert.Equal("lmnopqrstuvwxyz", newText.Segments[1].ToString()); } [Fact] public void TestAddingTextCreatesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(10, 0), "*"); Assert.Equal(27, textWithSegments.Length); Assert.Equal("abcdefghij*klmnopqrstuvwxyz", textWithSegments.ToString()); Assert.Equal(3, textWithSegments.Segments.Length); Assert.Equal("abcdefghij", textWithSegments.Segments[0].ToString()); Assert.Equal("*", textWithSegments.Segments[1].ToString()); Assert.Equal("klmnopqrstuvwxyz", textWithSegments.Segments[2].ToString()); } [Fact] public void TestRemovingAcrossExistingSegmentsRemovesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(10, 0), "*"); Assert.Equal(27, textWithSegments.Length); Assert.Equal(27, textWithSegments.StorageSize); var textWithFewerSegments = textWithSegments.Replace(new TextSpan(9, 3), ""); Assert.Equal("abcdefghilmnopqrstuvwxyz", textWithFewerSegments.ToString()); Assert.Equal(24, textWithFewerSegments.Length); Assert.Equal(26, textWithFewerSegments.StorageSize); Assert.Equal(2, textWithFewerSegments.Segments.Length); Assert.Equal("abcdefghi", textWithFewerSegments.Segments[0].ToString()); Assert.Equal("lmnopqrstuvwxyz", textWithFewerSegments.Segments[1].ToString()); } [Fact] public void TestRemovingEverythingSucceeds() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(0, text.Length), ""); Assert.Equal(0, textWithSegments.Length); Assert.Equal(0, textWithSegments.StorageSize); } [Fact] public void TestCompressingSegmentsCompressesSmallerSegmentsFirst() { var a = new string('a', 64); var b = new string('b', 64); var t = SourceText.From(a); t = t.Replace(t.Length, 0, b); // add b's var segs = t.Segments.Length; Assert.Equal(2, segs); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); // keep appending little segments until we trigger compression do { segs = t.Segments.Length; t = t.Replace(t.Length, 0, "c"); } while (t.Segments.Length > segs); // this should compact all the 'c' segments into one Assert.Equal(3, t.Segments.Length); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); Assert.Equal(new string('c', t.Segments[2].Length), t.Segments[2].ToString()); } [Fact] public void TestCompressingSegmentsCompressesLargerSegmentsIfNecessary() { var a = new string('a', 64); var b = new string('b', 64); var c = new string('c', 64); var t = SourceText.From(a); t = t.Replace(t.Length, 0, b); // add b's var segs = t.Segments.Length; Assert.Equal(2, segs); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); // keep appending larger segments (larger than initial size) do { segs = t.Segments.Length; t = t.Replace(t.Length, 0, c); // add c's that are the same segment size as the a's and b's } while (t.Segments.Length > segs); // this should compact all the segments since they all were the same size and // compress at the same time Assert.Equal(0, t.Segments.Length); } [Fact] public void TestOldEditsCanBeCollected() { // this test proves that intermediate edits are not being kept alive by successive edits. WeakReference weakFirstEdit; SourceText secondEdit; CreateEdits(out weakFirstEdit, out secondEdit); int tries = 0; while (weakFirstEdit.IsAlive) { tries++; if (tries > 10) { throw new InvalidOperationException("Failed to GC old edit"); } GC.Collect(2, GCCollectionMode.Forced, blocking: true); } } private void CreateEdits(out WeakReference weakFirstEdit, out SourceText secondEdit) { var text = SourceText.From("This is the old text"); var firstEdit = text.Replace(11, 3, "new"); secondEdit = firstEdit.Replace(11, 3, "newer"); weakFirstEdit = new WeakReference(firstEdit); } [Fact] public void TestLargeTextWriterReusesLargeChunks() { var chunk1 = "this is the large text".ToArray(); var largeText = CreateLargeText(chunk1); // chunks are considered large because they are bigger than the expected size var writer = new LargeTextWriter(largeText.Encoding, largeText.ChecksumAlgorithm, 10); largeText.Write(writer); var newText = (LargeText)writer.ToSourceText(); Assert.NotSame(largeText, newText); Assert.Equal(1, GetChunks(newText).Length); Assert.Same(chunk1, GetChunks(newText)[0]); } private SourceText CreateLargeText(params char[][] chunks) { return new LargeText(ImmutableArray.Create(chunks), Encoding.UTF8, default(ImmutableArray<byte>), SourceHashAlgorithm.Sha256, default(ImmutableArray<byte>)); } private ImmutableArray<char[]> GetChunks(SourceText text) { var largeText = text as LargeText; if (largeText != null) { var chunkField = text.GetType().GetField("_chunks", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); return (ImmutableArray<char[]>)chunkField.GetValue(text); } else { return ImmutableArray<char[]>.Empty; } } [Fact] public void TestLargeTextWriterDoesNotReuseSmallChunks() { var text = SourceText.From("small preamble"); var chunk1 = "this is the large text".ToArray(); var largeText = CreateLargeText(chunk1); // chunks are considered small because they fit within the buffer (which is the expected length for this test) var writer = new LargeTextWriter(largeText.Encoding, largeText.ChecksumAlgorithm, chunk1.Length * 4); // write preamble so buffer is allocated and has contents. text.Write(writer); // large text fits within the remaining buffer largeText.Write(writer); var newText = (LargeText)writer.ToSourceText(); Assert.NotSame(largeText, newText); Assert.Equal(text.Length + largeText.Length, newText.Length); Assert.Equal(1, GetChunks(newText).Length); Assert.NotSame(chunk1, GetChunks(newText)[0]); } [Fact] [WorkItem(10452, "https://github.com/dotnet/roslyn/issues/10452")] public void TestEmptyChangeAfterChange() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance var change2 = change1.WithChanges(); // this should not cause exception Assert.Same(change1, change2); // this was a no-op and returned the same instance } [Fact] [WorkItem(10452, "https://github.com/dotnet/roslyn/issues/10452")] public void TestEmptyChangeAfterChange2() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), string.Empty)); // this should not cause exception Assert.Same(change1, change2); // this was a no-op and returned the same instance } [Fact] public void TestMergeChanges_Overlapping_NewInsideOld() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 3), "oo")); Assert.Equal("Hello Cool World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 0), changes[0].Span); Assert.Equal("Cool ", changes[0].NewText); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndOldHasDeletion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0abba4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "abba") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndOldHasLeadingDeletion_SmallerThanLeadingInsertion() { var original = SourceText.From("012"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 1), "aaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(3, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aaa2", change1.ToString()); Assert.Equal("0aabba2", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 1), "aabba") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndBothHaveDeletion_NewDeletionSmallerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0abb4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "abb") }, changes); } [Fact] public void TestMergeChanges_Overlapping_OldInsideNew() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 14), "ar")); Assert.Equal("Heard", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(2, 8), changes[0].Span); Assert.Equal("ar", changes[0].NewText); } [Fact] public void TestMergeChanges_Overlapping_NewBeforeOld() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 6), " Bel")); Assert.Equal("Hell Bell World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 2), changes[0].Span); Assert.Equal(" Bell ", changes[0].NewText); } [Fact] public void TestMergeChanges_Overlapping_OldBeforeNew() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 6), "wazy V")); Assert.Equal("Hello Cwazy Vorld", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("Cwazy V", changes[0].NewText); } [Fact] public void TestMergeChanges_SameStart() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bbaa1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bbaa") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndOldHasDeletion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bbaa4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "bbaa") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_SmallerThanOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bba1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bba") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_EqualToOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 2), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bb1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bb") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_LargerThanOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bb234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 1), "bb") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_SameStart_AndBothHaveDeletion_NewDeletionSmallerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bba4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "bba") }, changes); } [Fact] [WorkItem(39405, "https://github.com/dotnet/roslyn/issues/39405")] public void TestMergeChanges_NewDeletionLargerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bb", change2.ToString()); } [Fact] public void TestMergeChanges_AfterAdjacent() { var original = SourceText.From("Hell"); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [Fact] public void TestMergeChanges_AfterSeparated() { var original = SourceText.From("Hell "); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o")); var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o", changes[0].NewText); Assert.Equal(new TextSpan(5, 0), changes[1].Span); Assert.Equal("World", changes[1].NewText); } [Fact] public void TestMergeChanges_BeforeSeparated() { var original = SourceText.From("Hell Word"); var change1 = original.WithChanges(new TextChange(new TextSpan(8, 0), "l")); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o", changes[0].NewText); Assert.Equal(new TextSpan(8, 0), changes[1].Span); Assert.Equal("l", changes[1].NewText); } [Fact] public void TestMergeChanges_BeforeAdjacent() { var original = SourceText.From("Hell"); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), " World")); Assert.Equal("Hell World", change1.ToString()); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10961")] public void TestMergeChanges_NoMiddleMan() { var original = SourceText.From("Hell"); var final = GetChangesWithoutMiddle( original, c => c.WithChanges(new TextChange(new TextSpan(4, 0), "o ")), c => c.WithChanges(new TextChange(new TextSpan(6, 0), "World"))); Assert.Equal("Hello World", final.ToString()); var changes = final.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [Fact] public void TestMergeChanges_IntegrationTestCase1() { var oldChanges = ImmutableArray.Create( new TextChangeRange(new TextSpan(919, 10), 466), new TextChangeRange(new TextSpan(936, 33), 29), new TextChangeRange(new TextSpan(1098, 0), 70), new TextChangeRange(new TextSpan(1125, 4), 34), new TextChangeRange(new TextSpan(1138, 0), 47)); var newChanges = ImmutableArray.Create( new TextChangeRange(new TextSpan(997, 0), 2), new TextChangeRange(new TextSpan(1414, 0), 2), new TextChangeRange(new TextSpan(1419, 0), 2), new TextChangeRange(new TextSpan(1671, 5), 5), new TextChangeRange(new TextSpan(1681, 0), 4)); var merged = ChangedText.TestAccessor.Merge(oldChanges, newChanges); var expected = ImmutableArray.Create( new TextChangeRange(new TextSpan(919, 10), 468), new TextChangeRange(new TextSpan(936, 33), 33), new TextChangeRange(new TextSpan(1098, 0), 70), new TextChangeRange(new TextSpan(1125, 4), 38), new TextChangeRange(new TextSpan(1138, 0), 47)); Assert.Equal<TextChangeRange>(expected, merged); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void DebuggerDisplay() { Assert.Equal("new TextChange(new TextSpan(0, 0), null)", default(TextChange).GetDebuggerDisplay()); Assert.Equal("new TextChange(new TextSpan(0, 1), \"abc\")", new TextChange(new TextSpan(0, 1), "abc").GetDebuggerDisplay()); Assert.Equal("new TextChange(new TextSpan(0, 1), (NewLength = 10))", new TextChange(new TextSpan(0, 1), "0123456789").GetDebuggerDisplay()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz() { var random = new Random(); // Adjust upper bound as needed to generate a simpler reproducer for an error scenario var originalText = SourceText.From(string.Join("", Enumerable.Range(0, random.Next(10)))); for (var iteration = 0; iteration < 100000; iteration++) { var editedLength = originalText.Length; ArrayBuilder<TextChange> oldChangesBuilder = ArrayBuilder<TextChange>.GetInstance(); // Adjust as needed to get a simpler error reproducer. var oldMaxInsertLength = originalText.Length * 2; const int maxSkipLength = 2; // generate sequence of "old edits" which meet invariants for (int i = 0; i < originalText.Length; i += random.Next(maxSkipLength)) { var newText = string.Join("", Enumerable.Repeat('a', random.Next(oldMaxInsertLength))); var newChange = new TextChange(new TextSpan(i, length: random.Next(originalText.Length - i)), newText); i = newChange.Span.End; editedLength = editedLength - newChange.Span.Length + newChange.NewText.Length; oldChangesBuilder.Add(newChange); // Adjust as needed to generate a simpler reproducer for an error scenario if (oldChangesBuilder.Count == 5) break; } var change1 = originalText.WithChanges(oldChangesBuilder); ArrayBuilder<TextChange> newChangesBuilder = ArrayBuilder<TextChange>.GetInstance(); // Adjust as needed to get a simpler error reproducer. var newMaxInsertLength = editedLength * 2; // generate sequence of "new edits" which meet invariants for (int i = 0; i < editedLength; i += random.Next(maxSkipLength)) { var newText = string.Join("", Enumerable.Repeat('b', random.Next(newMaxInsertLength))); var newChange = new TextChange(new TextSpan(i, length: random.Next(editedLength - i)), newText); i = newChange.Span.End; newChangesBuilder.Add(newChange); // Adjust as needed to generate a simpler reproducer for an error scenario if (newChangesBuilder.Count == 5) break; } var change2 = change1.WithChanges(newChangesBuilder); try { var textChanges = change2.GetTextChanges(originalText); Assert.Equal(originalText.WithChanges(textChanges).ToString(), change2.ToString()); } catch { _output.WriteLine($@" [Fact] public void Fuzz_{iteration}() {{ var originalText = SourceText.From(""{originalText}""); var change1 = originalText.WithChanges({string.Join(", ", oldChangesBuilder.Select(c => c.GetDebuggerDisplay()))}); var change2 = change1.WithChanges({string.Join(", ", newChangesBuilder.Select(c => c.GetDebuggerDisplay()))}); Assert.Equal(""{change1}"", change1.ToString()); // double-check for correctness Assert.Equal(""{change2}"", change2.ToString()); // double-check for correctness var changes = change2.GetTextChanges(originalText); Assert.Equal(""{change2}"", originalText.WithChanges(changes).ToString()); }} "); throw; } finally { // we delay freeing so that if we need to debug the fuzzer // it's easier to see what changes were introduced at each stage. oldChangesBuilder.Free(); newChangesBuilder.Free(); } } } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_0() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), "bb")); Assert.Equal("a234", change1.ToString()); Assert.Equal("bb34", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bb34", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_1() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(0, 0), "aa"), new TextChange(new TextSpan(1, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), "")); var changes = change2.GetTextChanges(original); Assert.Equal("aa0aa234", change1.ToString()); Assert.Equal("baa234", change2.ToString()); Assert.Equal(change2.ToString(), original.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_2() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 0), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(2, 0), "bb")); Assert.Equal("a01234", change1.ToString()); Assert.Equal("bb1234", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bb1234", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_3() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa"), new TextChange(new TextSpan(3, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "bbb")); Assert.Equal("aa12aa4", change1.ToString()); Assert.Equal("bbbaa12aa4", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bbbaa12aa4", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_4() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 3), "a"), new TextChange(new TextSpan(5, 0), "aaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), "bb")); Assert.Equal("a34aaa5", change1.ToString()); Assert.Equal("4bbaa5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("4bbaa5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_7() { var originalText = SourceText.From("01234567"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aaaaa"), new TextChange(new TextSpan(3, 1), "aaaa"), new TextChange(new TextSpan(6, 1), "aaaaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(2, 0), "b"), new TextChange(new TextSpan(3, 4), "bbbbb"), new TextChange(new TextSpan(9, 5), "bbbbb"), new TextChange(new TextSpan(15, 3), "")); Assert.Equal("aaaaa12aaaa45aaaaa7", change1.ToString()); Assert.Equal("baababbbbbaabbbbba7", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("baababbbbbaabbbbba7", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_10() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), "b")); Assert.Equal("a1234", change1.ToString()); Assert.Equal("b1b4", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("b1b4", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_23() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(1, 2), "b")); Assert.Equal("aa1234", change1.ToString()); Assert.Equal("bab234", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bab234", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_32() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a"), new TextChange(new TextSpan(3, 2), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 3), "bbb")); Assert.Equal("a2a5", change1.ToString()); Assert.Equal("bbb5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bbb5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_39() { var originalText = SourceText.From("0123456"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 4), ""), new TextChange(new TextSpan(5, 1), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 0), "")); Assert.Equal("46", change1.ToString()); Assert.Equal("6", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("6", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_55() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 1), ""), new TextChange(new TextSpan(2, 0), "")); Assert.Equal("245", change1.ToString()); Assert.Equal("5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_110() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(2, 1), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), ""), new TextChange(new TextSpan(1, 1), "")); Assert.Equal("134", change1.ToString()); Assert.Equal("14", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("14", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(41413, "https://github.com/dotnet/roslyn/issues/41413")] public void GetTextChanges_NonOverlappingSpans() { var content = @"@functions{ public class Foo { void Method() { } } }"; var text = SourceText.From(content); var edits1 = new TextChange[] { new TextChange(new TextSpan(39, 0), " "), new TextChange(new TextSpan(42, 0), " "), new TextChange(new TextSpan(57, 0), " "), new TextChange(new TextSpan(58, 0), "\r\n"), new TextChange(new TextSpan(64, 2), " "), new TextChange(new TextSpan(69, 0), " "), }; var changedText = text.WithChanges(edits1); var edits2 = new TextChange[] { new TextChange(new TextSpan(35, 4), string.Empty), new TextChange(new TextSpan(46, 4), string.Empty), new TextChange(new TextSpan(73, 4), string.Empty), new TextChange(new TextSpan(88, 0), " "), new TextChange(new TextSpan(90, 4), string.Empty), new TextChange(new TextSpan(105, 4), string.Empty), }; var changedText2 = changedText.WithChanges(edits2); var changes = changedText2.GetTextChanges(text); var position = 0; foreach (var change in changes) { Assert.True(position <= change.Span.Start); position = change.Span.End; } } private SourceText GetChangesWithoutMiddle( SourceText original, Func<SourceText, SourceText> fnChange1, Func<SourceText, SourceText> fnChange2) { WeakReference change1; SourceText change2; GetChangesWithoutMiddle_Helper(original, fnChange1, fnChange2, out change1, out change2); while (change1.IsAlive) { GC.Collect(2); GC.WaitForFullGCComplete(); } return change2; } private void GetChangesWithoutMiddle_Helper( SourceText original, Func<SourceText, SourceText> fnChange1, Func<SourceText, SourceText> fnChange2, out WeakReference change1, out SourceText change2) { var c1 = fnChange1(original); change1 = new WeakReference(c1); change2 = fnChange2(c1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { public class TextChangeTests { private readonly ITestOutputHelper _output; public TextChangeTests(ITestOutputHelper output) { _output = output; } [Fact] public void TestSubTextStart() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(6); Assert.Equal("World", subText.ToString()); } [Fact] public void TestSubTextSpanFirst() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(0, 5)); Assert.Equal("Hello", subText.ToString()); } [Fact] public void TestSubTextSpanLast() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(6, 5)); Assert.Equal("World", subText.ToString()); } [Fact] public void TestSubTextSpanMid() { var text = SourceText.From("Hello World"); var subText = text.GetSubText(new TextSpan(4, 3)); Assert.Equal("o W", subText.ToString()); } [Fact] public void TestChangedText() { var text = SourceText.From("Hello World"); var newText = text.Replace(6, 0, "Beautiful "); Assert.Equal("Hello Beautiful World", newText.ToString()); } [Fact] public void TestChangedTextChanges() { var text = SourceText.From("Hello World"); var newText = text.Replace(6, 0, "Beautiful "); var changes = newText.GetChangeRanges(text); Assert.NotNull(changes); Assert.Equal(1, changes.Count); Assert.Equal(6, changes[0].Span.Start); Assert.Equal(0, changes[0].Span.Length); Assert.Equal(10, changes[0].NewLength); } [Fact] public void TestChangedTextWithMultipleChanges() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(0, 5), "Halo"), new TextChange(new TextSpan(6, 5), "Universe")); Assert.Equal("Halo Universe", newText.ToString()); } [Fact] public void TestChangedTextWithMultipleOverlappingChanges() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(0, 5), "Halo"), new TextChange(new TextSpan(3, 5), "Universe") }; Assert.Throws<ArgumentException>(() => text.WithChanges(changes)); } [Fact] public void TestChangedTextWithMultipleUnorderedChanges() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 5), "Universe"), new TextChange(new TextSpan(0, 5), "Halo") }; var newText = text.WithChanges(changes); Assert.Equal("Halo Universe", newText.ToString()); } [Fact] public void TestChangedTextWithMultipleUnorderedChangesAndOneIsOutOfBounds() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 7), "Universe"), new TextChange(new TextSpan(0, 5), "Halo") }; Assert.ThrowsAny<ArgumentException>(() => { var newText = text.WithChanges(changes); }); } [Fact] public void TestChangedTextWithMultipleConsecutiveInsertsSamePosition() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 0), "Super "), new TextChange(new TextSpan(6, 0), "Spectacular ")); Assert.Equal("Hello Super Spectacular World", newText.ToString()); } [Fact] public void TestChangedTextWithReplaceAfterInsertSamePosition() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 0), "Super "), new TextChange(new TextSpan(6, 2), "Vu")); Assert.Equal("Hello Super Vurld", newText.ToString()); } [Fact] public void TestChangedTextWithReplaceBeforeInsertSamePosition() { var text = SourceText.From("Hello World"); var changes = new[] { new TextChange(new TextSpan(6, 2), "Vu"), new TextChange(new TextSpan(6, 0), "Super ") }; var newText = text.WithChanges(changes); Assert.Equal("Hello Super Vurld", newText.ToString()); } [Fact] public void TestChangedTextWithDeleteAfterDeleteAdjacent() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty), new TextChange(new TextSpan(5, 1), string.Empty)); Assert.Equal("HellWorld", newText.ToString()); } [Fact] public void TestSubTextAfterMultipleChanges() { var text = SourceText.From("Hello World", Encoding.Unicode, SourceHashAlgorithm.Sha256); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty), new TextChange(new TextSpan(6, 5), "Universe")); var subText = newText.GetSubText(new TextSpan(3, 4)); Assert.Equal("l Un", subText.ToString()); Assert.Equal(SourceHashAlgorithm.Sha256, subText.ChecksumAlgorithm); Assert.Same(Encoding.Unicode, subText.Encoding); } [Fact] public void TestLinesInChangedText() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(4, 1), string.Empty)); Assert.Equal(1, newText.Lines.Count); } [Fact] public void TestCopyTo() { var text = SourceText.From("Hello World"); var newText = text.WithChanges( new TextChange(new TextSpan(6, 5), "Universe")); var destination = new char[32]; newText.CopyTo(0, destination, 0, 0); //should copy nothing and not throw. Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(-1, destination, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, -1, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, 0, -1)); Assert.Throws<ArgumentNullException>(() => newText.CopyTo(0, null, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(newText.Length - 1, destination, 0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => newText.CopyTo(0, destination, destination.Length - 1, 2)); } [Fact] public void TestGetTextChangesToChangedText() { var text = SourceText.From(new string('.', 2048), Encoding.Unicode, SourceHashAlgorithm.Sha256); // start bigger than GetText() copy buffer var changes = new TextChange[] { new TextChange(new TextSpan(0, 1), "[1]"), new TextChange(new TextSpan(1, 1), "[2]"), new TextChange(new TextSpan(5, 0), "[3]"), new TextChange(new TextSpan(25, 2), "[4]") }; var newText = text.WithChanges(changes); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); Assert.Same(Encoding.Unicode, newText.Encoding); var result = newText.GetTextChanges(text).ToList(); Assert.Equal(changes.Length, result.Count); for (int i = 0; i < changes.Length; i++) { var expected = changes[i]; var actual = result[i]; Assert.Equal(expected.Span, actual.Span); Assert.Equal(expected.NewText, actual.NewText); } } private sealed class TextLineEqualityComparer : IEqualityComparer<TextLine> { public bool Equals(TextLine x, TextLine y) { return x.Span == y.Span; } public int GetHashCode(TextLine obj) { return obj.Span.GetHashCode(); } } private static void AssertChangedTextLinesHelper(string originalText, params TextChange[] changes) { var changedText = SourceText.From(originalText).WithChanges(changes); Assert.Equal(SourceText.From(changedText.ToString()).Lines, changedText.Lines, new TextLineEqualityComparer()); } [Fact] public void TestOptimizedSourceTextLinesSimpleSubstitution() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), "IN"), new TextChange(new TextSpan(15, 2), "IN")); } [Fact] public void TestOptimizedSourceTextLinesSubstitutionWithLongerText() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), new string('a', 10)), new TextChange(new TextSpan(15, 2), new string('a', 10))); } [Fact] public void TestOptimizedSourceTextLinesInsertCrLf() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(8, 2), "\r\n"), new TextChange(new TextSpan(15, 2), "\r\n")); } [Fact] public void TestOptimizedSourceTextLinesSimpleCr() { AssertChangedTextLinesHelper("Line1\rLine2\rLine3", new TextChange(new TextSpan(6, 0), "aa\r"), new TextChange(new TextSpan(11, 0), "aa\r")); } [Fact] public void TestOptimizedSourceTextLinesSimpleLf() { AssertChangedTextLinesHelper("Line1\nLine2\nLine3", new TextChange(new TextSpan(6, 0), "aa\n"), new TextChange(new TextSpan(11, 0), "aa\n")); } [Fact] public void TestOptimizedSourceTextLinesRemoveCrLf() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3", new TextChange(new TextSpan(4, 4), "aaaaaa"), new TextChange(new TextSpan(15, 4), "aaaaaa")); } [Fact] public void TestOptimizedSourceTextLinesBrakeCrLf() { AssertChangedTextLinesHelper("Test\r\nMessage", new TextChange(new TextSpan(5, 0), "aaaaaa")); } [Fact] public void TestOptimizedSourceTextLinesBrakeCrLfWithLfPrefixedAndCrSuffixed() { AssertChangedTextLinesHelper("Test\r\nMessage", new TextChange(new TextSpan(5, 0), "\naaaaaa\r")); } [Fact] public void TestOptimizedSourceTextLineInsertAtEnd() { AssertChangedTextLinesHelper("Line1\r\nLine2\r\nLine3\r\n", new TextChange(new TextSpan(21, 0), "Line4\r\n"), new TextChange(new TextSpan(21, 0), "Line5\r\n")); } [Fact] public void TestManySingleCharacterAdds() { var str = new String('.', 1024); var text = SourceText.From(str); var lines = text.Lines; int n = 20000; var expected = str; for (int i = 0; i < n; i++) { char c = (char)(((ushort)'a') + (i % 26)); text = text.Replace(50 + i, 0, c.ToString()); expected = expected.Substring(0, 50 + i) + c + expected.Substring(50 + i); } Assert.Equal(str.Length + n, text.Length); Assert.Equal(expected, text.ToString()); } [Fact] public void TestManySingleCharacterReplacements() { var str = new String('.', 1024); var text = SourceText.From(str); var lines = text.Lines; var expected = str; for (int i = 0; i < str.Length; i++) { char c = (char)(((ushort)'a') + (i % 26)); text = text.Replace(i, 1, c.ToString()); expected = expected.Substring(0, i) + c + str.Substring(i + 1); } Assert.Equal(str.Length, text.Length); Assert.Equal(expected, text.ToString()); } [Fact] public void TestSubTextCausesSizeLengthDifference() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(26, text.Length); Assert.Equal(26, text.StorageSize); var subtext = text.GetSubText(new TextSpan(5, 10)); Assert.Equal(10, subtext.Length); Assert.Equal("fghijklmno", subtext.ToString()); Assert.Equal(26, subtext.StorageSize); } [Fact] public void TestRemovingMajorityOfTextCompressesStorage() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); var newText = text.Replace(new TextSpan(0, 20), ""); Assert.Equal(6, newText.Length); Assert.Equal(6, newText.StorageSize); } [Fact] public void TestRemovingMinorityOfTextDoesNotCompressesStorage() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); var newText = text.Replace(new TextSpan(10, 6), ""); Assert.Equal(20, newText.Length); Assert.Equal(26, newText.StorageSize); } [Fact] public void TestRemovingTextCreatesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var newText = text.Replace(new TextSpan(10, 1), ""); Assert.Equal(25, newText.Length); Assert.Equal(26, newText.StorageSize); Assert.Equal(2, newText.Segments.Length); Assert.Equal("abcdefghij", newText.Segments[0].ToString()); Assert.Equal("lmnopqrstuvwxyz", newText.Segments[1].ToString()); } [Fact] public void TestAddingTextCreatesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(10, 0), "*"); Assert.Equal(27, textWithSegments.Length); Assert.Equal("abcdefghij*klmnopqrstuvwxyz", textWithSegments.ToString()); Assert.Equal(3, textWithSegments.Segments.Length); Assert.Equal("abcdefghij", textWithSegments.Segments[0].ToString()); Assert.Equal("*", textWithSegments.Segments[1].ToString()); Assert.Equal("klmnopqrstuvwxyz", textWithSegments.Segments[2].ToString()); } [Fact] public void TestRemovingAcrossExistingSegmentsRemovesSegments() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(10, 0), "*"); Assert.Equal(27, textWithSegments.Length); Assert.Equal(27, textWithSegments.StorageSize); var textWithFewerSegments = textWithSegments.Replace(new TextSpan(9, 3), ""); Assert.Equal("abcdefghilmnopqrstuvwxyz", textWithFewerSegments.ToString()); Assert.Equal(24, textWithFewerSegments.Length); Assert.Equal(26, textWithFewerSegments.StorageSize); Assert.Equal(2, textWithFewerSegments.Segments.Length); Assert.Equal("abcdefghi", textWithFewerSegments.Segments[0].ToString()); Assert.Equal("lmnopqrstuvwxyz", textWithFewerSegments.Segments[1].ToString()); } [Fact] public void TestRemovingEverythingSucceeds() { var text = SourceText.From("abcdefghijklmnopqrstuvwxyz"); Assert.Equal(0, text.Segments.Length); var textWithSegments = text.Replace(new TextSpan(0, text.Length), ""); Assert.Equal(0, textWithSegments.Length); Assert.Equal(0, textWithSegments.StorageSize); } [Fact] public void TestCompressingSegmentsCompressesSmallerSegmentsFirst() { var a = new string('a', 64); var b = new string('b', 64); var t = SourceText.From(a); t = t.Replace(t.Length, 0, b); // add b's var segs = t.Segments.Length; Assert.Equal(2, segs); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); // keep appending little segments until we trigger compression do { segs = t.Segments.Length; t = t.Replace(t.Length, 0, "c"); } while (t.Segments.Length > segs); // this should compact all the 'c' segments into one Assert.Equal(3, t.Segments.Length); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); Assert.Equal(new string('c', t.Segments[2].Length), t.Segments[2].ToString()); } [Fact] public void TestCompressingSegmentsCompressesLargerSegmentsIfNecessary() { var a = new string('a', 64); var b = new string('b', 64); var c = new string('c', 64); var t = SourceText.From(a); t = t.Replace(t.Length, 0, b); // add b's var segs = t.Segments.Length; Assert.Equal(2, segs); Assert.Equal(a, t.Segments[0].ToString()); Assert.Equal(b, t.Segments[1].ToString()); // keep appending larger segments (larger than initial size) do { segs = t.Segments.Length; t = t.Replace(t.Length, 0, c); // add c's that are the same segment size as the a's and b's } while (t.Segments.Length > segs); // this should compact all the segments since they all were the same size and // compress at the same time Assert.Equal(0, t.Segments.Length); } [Fact] public void TestOldEditsCanBeCollected() { // this test proves that intermediate edits are not being kept alive by successive edits. WeakReference weakFirstEdit; SourceText secondEdit; CreateEdits(out weakFirstEdit, out secondEdit); int tries = 0; while (weakFirstEdit.IsAlive) { tries++; if (tries > 10) { throw new InvalidOperationException("Failed to GC old edit"); } GC.Collect(2, GCCollectionMode.Forced, blocking: true); } } private void CreateEdits(out WeakReference weakFirstEdit, out SourceText secondEdit) { var text = SourceText.From("This is the old text"); var firstEdit = text.Replace(11, 3, "new"); secondEdit = firstEdit.Replace(11, 3, "newer"); weakFirstEdit = new WeakReference(firstEdit); } [Fact] public void TestLargeTextWriterReusesLargeChunks() { var chunk1 = "this is the large text".ToArray(); var largeText = CreateLargeText(chunk1); // chunks are considered large because they are bigger than the expected size var writer = new LargeTextWriter(largeText.Encoding, largeText.ChecksumAlgorithm, 10); largeText.Write(writer); var newText = (LargeText)writer.ToSourceText(); Assert.NotSame(largeText, newText); Assert.Equal(1, GetChunks(newText).Length); Assert.Same(chunk1, GetChunks(newText)[0]); } private SourceText CreateLargeText(params char[][] chunks) { return new LargeText(ImmutableArray.Create(chunks), Encoding.UTF8, default(ImmutableArray<byte>), SourceHashAlgorithm.Sha256, default(ImmutableArray<byte>)); } private ImmutableArray<char[]> GetChunks(SourceText text) { var largeText = text as LargeText; if (largeText != null) { var chunkField = text.GetType().GetField("_chunks", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); return (ImmutableArray<char[]>)chunkField.GetValue(text); } else { return ImmutableArray<char[]>.Empty; } } [Fact] public void TestLargeTextWriterDoesNotReuseSmallChunks() { var text = SourceText.From("small preamble"); var chunk1 = "this is the large text".ToArray(); var largeText = CreateLargeText(chunk1); // chunks are considered small because they fit within the buffer (which is the expected length for this test) var writer = new LargeTextWriter(largeText.Encoding, largeText.ChecksumAlgorithm, chunk1.Length * 4); // write preamble so buffer is allocated and has contents. text.Write(writer); // large text fits within the remaining buffer largeText.Write(writer); var newText = (LargeText)writer.ToSourceText(); Assert.NotSame(largeText, newText); Assert.Equal(text.Length + largeText.Length, newText.Length); Assert.Equal(1, GetChunks(newText).Length); Assert.NotSame(chunk1, GetChunks(newText)[0]); } [Fact] [WorkItem(10452, "https://github.com/dotnet/roslyn/issues/10452")] public void TestEmptyChangeAfterChange() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance var change2 = change1.WithChanges(); // this should not cause exception Assert.Same(change1, change2); // this was a no-op and returned the same instance } [Fact] [WorkItem(10452, "https://github.com/dotnet/roslyn/issues/10452")] public void TestEmptyChangeAfterChange2() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), string.Empty)); // this should not cause exception Assert.Same(change1, change2); // this was a no-op and returned the same instance } [Fact] public void TestMergeChanges_Overlapping_NewInsideOld() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 3), "oo")); Assert.Equal("Hello Cool World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 0), changes[0].Span); Assert.Equal("Cool ", changes[0].NewText); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndOldHasDeletion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0abba4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "abba") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndOldHasLeadingDeletion_SmallerThanLeadingInsertion() { var original = SourceText.From("012"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 1), "aaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(3, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aaa2", change1.ToString()); Assert.Equal("0aabba2", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 1), "aabba") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_Overlapping_NewInsideOld_AndBothHaveDeletion_NewDeletionSmallerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0abb4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "abb") }, changes); } [Fact] public void TestMergeChanges_Overlapping_OldInsideNew() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 14), "ar")); Assert.Equal("Heard", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(2, 8), changes[0].Span); Assert.Equal("ar", changes[0].NewText); } [Fact] public void TestMergeChanges_Overlapping_NewBeforeOld() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 6), " Bel")); Assert.Equal("Hell Bell World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 2), changes[0].Span); Assert.Equal(" Bell ", changes[0].NewText); } [Fact] public void TestMergeChanges_Overlapping_OldBeforeNew() { var original = SourceText.From("Hello World"); var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 6), "wazy V")); Assert.Equal("Hello Cwazy Vorld", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(6, 1), changes[0].Span); Assert.Equal("Cwazy V", changes[0].NewText); } [Fact] public void TestMergeChanges_SameStart() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bbaa1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bbaa") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndOldHasDeletion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bbaa4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "bbaa") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_SmallerThanOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bba1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bba") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_EqualToOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 2), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bb1234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 0), "bb") }, changes); } [Fact] public void TestMergeChanges_SameStart_AndNewHasDeletion_LargerThanOldInsertion() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa1234", change1.ToString()); Assert.Equal("0bb234", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 1), "bb") }, changes); } [Fact] [WorkItem(22289, "https://github.com/dotnet/roslyn/issues/22289")] public void TestMergeChanges_SameStart_AndBothHaveDeletion_NewDeletionSmallerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bba4", change2.ToString()); Assert.Equal(new[] { new TextChange(new TextSpan(1, 3), "bba") }, changes); } [Fact] [WorkItem(39405, "https://github.com/dotnet/roslyn/issues/39405")] public void TestMergeChanges_NewDeletionLargerThanOld() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb")); var changes = change2.GetTextChanges(original); Assert.Equal("0aa4", change1.ToString()); Assert.Equal("0bb", change2.ToString()); } [Fact] public void TestMergeChanges_AfterAdjacent() { var original = SourceText.From("Hell"); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o ")); var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [Fact] public void TestMergeChanges_AfterSeparated() { var original = SourceText.From("Hell "); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o")); var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o", changes[0].NewText); Assert.Equal(new TextSpan(5, 0), changes[1].Span); Assert.Equal("World", changes[1].NewText); } [Fact] public void TestMergeChanges_BeforeSeparated() { var original = SourceText.From("Hell Word"); var change1 = original.WithChanges(new TextChange(new TextSpan(8, 0), "l")); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(2, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o", changes[0].NewText); Assert.Equal(new TextSpan(8, 0), changes[1].Span); Assert.Equal("l", changes[1].NewText); } [Fact] public void TestMergeChanges_BeforeAdjacent() { var original = SourceText.From("Hell"); var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), " World")); Assert.Equal("Hell World", change1.ToString()); var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o")); Assert.Equal("Hello World", change2.ToString()); var changes = change2.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10961")] public void TestMergeChanges_NoMiddleMan() { var original = SourceText.From("Hell"); var final = GetChangesWithoutMiddle( original, c => c.WithChanges(new TextChange(new TextSpan(4, 0), "o ")), c => c.WithChanges(new TextChange(new TextSpan(6, 0), "World"))); Assert.Equal("Hello World", final.ToString()); var changes = final.GetTextChanges(original); Assert.Equal(1, changes.Count); Assert.Equal(new TextSpan(4, 0), changes[0].Span); Assert.Equal("o World", changes[0].NewText); } [Fact] public void TestMergeChanges_IntegrationTestCase1() { var oldChanges = ImmutableArray.Create( new TextChangeRange(new TextSpan(919, 10), 466), new TextChangeRange(new TextSpan(936, 33), 29), new TextChangeRange(new TextSpan(1098, 0), 70), new TextChangeRange(new TextSpan(1125, 4), 34), new TextChangeRange(new TextSpan(1138, 0), 47)); var newChanges = ImmutableArray.Create( new TextChangeRange(new TextSpan(997, 0), 2), new TextChangeRange(new TextSpan(1414, 0), 2), new TextChangeRange(new TextSpan(1419, 0), 2), new TextChangeRange(new TextSpan(1671, 5), 5), new TextChangeRange(new TextSpan(1681, 0), 4)); var merged = ChangedText.TestAccessor.Merge(oldChanges, newChanges); var expected = ImmutableArray.Create( new TextChangeRange(new TextSpan(919, 10), 468), new TextChangeRange(new TextSpan(936, 33), 33), new TextChangeRange(new TextSpan(1098, 0), 70), new TextChangeRange(new TextSpan(1125, 4), 38), new TextChangeRange(new TextSpan(1138, 0), 47)); Assert.Equal<TextChangeRange>(expected, merged); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void DebuggerDisplay() { Assert.Equal("new TextChange(new TextSpan(0, 0), null)", default(TextChange).GetDebuggerDisplay()); Assert.Equal("new TextChange(new TextSpan(0, 1), \"abc\")", new TextChange(new TextSpan(0, 1), "abc").GetDebuggerDisplay()); Assert.Equal("new TextChange(new TextSpan(0, 1), (NewLength = 10))", new TextChange(new TextSpan(0, 1), "0123456789").GetDebuggerDisplay()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz() { var random = new Random(); // Adjust upper bound as needed to generate a simpler reproducer for an error scenario var originalText = SourceText.From(string.Join("", Enumerable.Range(0, random.Next(10)))); for (var iteration = 0; iteration < 100000; iteration++) { var editedLength = originalText.Length; ArrayBuilder<TextChange> oldChangesBuilder = ArrayBuilder<TextChange>.GetInstance(); // Adjust as needed to get a simpler error reproducer. var oldMaxInsertLength = originalText.Length * 2; const int maxSkipLength = 2; // generate sequence of "old edits" which meet invariants for (int i = 0; i < originalText.Length; i += random.Next(maxSkipLength)) { var newText = string.Join("", Enumerable.Repeat('a', random.Next(oldMaxInsertLength))); var newChange = new TextChange(new TextSpan(i, length: random.Next(originalText.Length - i)), newText); i = newChange.Span.End; editedLength = editedLength - newChange.Span.Length + newChange.NewText.Length; oldChangesBuilder.Add(newChange); // Adjust as needed to generate a simpler reproducer for an error scenario if (oldChangesBuilder.Count == 5) break; } var change1 = originalText.WithChanges(oldChangesBuilder); ArrayBuilder<TextChange> newChangesBuilder = ArrayBuilder<TextChange>.GetInstance(); // Adjust as needed to get a simpler error reproducer. var newMaxInsertLength = editedLength * 2; // generate sequence of "new edits" which meet invariants for (int i = 0; i < editedLength; i += random.Next(maxSkipLength)) { var newText = string.Join("", Enumerable.Repeat('b', random.Next(newMaxInsertLength))); var newChange = new TextChange(new TextSpan(i, length: random.Next(editedLength - i)), newText); i = newChange.Span.End; newChangesBuilder.Add(newChange); // Adjust as needed to generate a simpler reproducer for an error scenario if (newChangesBuilder.Count == 5) break; } var change2 = change1.WithChanges(newChangesBuilder); try { var textChanges = change2.GetTextChanges(originalText); Assert.Equal(originalText.WithChanges(textChanges).ToString(), change2.ToString()); } catch { _output.WriteLine($@" [Fact] public void Fuzz_{iteration}() {{ var originalText = SourceText.From(""{originalText}""); var change1 = originalText.WithChanges({string.Join(", ", oldChangesBuilder.Select(c => c.GetDebuggerDisplay()))}); var change2 = change1.WithChanges({string.Join(", ", newChangesBuilder.Select(c => c.GetDebuggerDisplay()))}); Assert.Equal(""{change1}"", change1.ToString()); // double-check for correctness Assert.Equal(""{change2}"", change2.ToString()); // double-check for correctness var changes = change2.GetTextChanges(originalText); Assert.Equal(""{change2}"", originalText.WithChanges(changes).ToString()); }} "); throw; } finally { // we delay freeing so that if we need to debug the fuzzer // it's easier to see what changes were introduced at each stage. oldChangesBuilder.Free(); newChangesBuilder.Free(); } } } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_0() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), "bb")); Assert.Equal("a234", change1.ToString()); Assert.Equal("bb34", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bb34", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_1() { var original = SourceText.From("01234"); var change1 = original.WithChanges(new TextChange(new TextSpan(0, 0), "aa"), new TextChange(new TextSpan(1, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), "")); var changes = change2.GetTextChanges(original); Assert.Equal("aa0aa234", change1.ToString()); Assert.Equal("baa234", change2.ToString()); Assert.Equal(change2.ToString(), original.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_2() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 0), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(2, 0), "bb")); Assert.Equal("a01234", change1.ToString()); Assert.Equal("bb1234", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bb1234", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_3() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa"), new TextChange(new TextSpan(3, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "bbb")); Assert.Equal("aa12aa4", change1.ToString()); Assert.Equal("bbbaa12aa4", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bbbaa12aa4", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_4() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 3), "a"), new TextChange(new TextSpan(5, 0), "aaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), "bb")); Assert.Equal("a34aaa5", change1.ToString()); Assert.Equal("4bbaa5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("4bbaa5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_7() { var originalText = SourceText.From("01234567"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aaaaa"), new TextChange(new TextSpan(3, 1), "aaaa"), new TextChange(new TextSpan(6, 1), "aaaaa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(2, 0), "b"), new TextChange(new TextSpan(3, 4), "bbbbb"), new TextChange(new TextSpan(9, 5), "bbbbb"), new TextChange(new TextSpan(15, 3), "")); Assert.Equal("aaaaa12aaaa45aaaaa7", change1.ToString()); Assert.Equal("baababbbbbaabbbbba7", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("baababbbbbaabbbbba7", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_10() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), "b")); Assert.Equal("a1234", change1.ToString()); Assert.Equal("b1b4", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("b1b4", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_23() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(1, 2), "b")); Assert.Equal("aa1234", change1.ToString()); Assert.Equal("bab234", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bab234", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_32() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a"), new TextChange(new TextSpan(3, 2), "a")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 3), "bbb")); Assert.Equal("a2a5", change1.ToString()); Assert.Equal("bbb5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("bbb5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_39() { var originalText = SourceText.From("0123456"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 4), ""), new TextChange(new TextSpan(5, 1), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 0), "")); Assert.Equal("46", change1.ToString()); Assert.Equal("6", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("6", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_55() { var originalText = SourceText.From("012345"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 1), ""), new TextChange(new TextSpan(2, 0), "")); Assert.Equal("245", change1.ToString()); Assert.Equal("5", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("5", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(47234, "https://github.com/dotnet/roslyn/issues/47234")] public void Fuzz_110() { var originalText = SourceText.From("01234"); var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(2, 1), "")); var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), ""), new TextChange(new TextSpan(1, 1), "")); Assert.Equal("134", change1.ToString()); Assert.Equal("14", change2.ToString()); var changes = change2.GetTextChanges(originalText); Assert.Equal("14", originalText.WithChanges(changes).ToString()); } [Fact] [WorkItem(41413, "https://github.com/dotnet/roslyn/issues/41413")] public void GetTextChanges_NonOverlappingSpans() { var content = @"@functions{ public class Foo { void Method() { } } }"; var text = SourceText.From(content); var edits1 = new TextChange[] { new TextChange(new TextSpan(39, 0), " "), new TextChange(new TextSpan(42, 0), " "), new TextChange(new TextSpan(57, 0), " "), new TextChange(new TextSpan(58, 0), "\r\n"), new TextChange(new TextSpan(64, 2), " "), new TextChange(new TextSpan(69, 0), " "), }; var changedText = text.WithChanges(edits1); var edits2 = new TextChange[] { new TextChange(new TextSpan(35, 4), string.Empty), new TextChange(new TextSpan(46, 4), string.Empty), new TextChange(new TextSpan(73, 4), string.Empty), new TextChange(new TextSpan(88, 0), " "), new TextChange(new TextSpan(90, 4), string.Empty), new TextChange(new TextSpan(105, 4), string.Empty), }; var changedText2 = changedText.WithChanges(edits2); var changes = changedText2.GetTextChanges(text); var position = 0; foreach (var change in changes) { Assert.True(position <= change.Span.Start); position = change.Span.End; } } private SourceText GetChangesWithoutMiddle( SourceText original, Func<SourceText, SourceText> fnChange1, Func<SourceText, SourceText> fnChange2) { WeakReference change1; SourceText change2; GetChangesWithoutMiddle_Helper(original, fnChange1, fnChange2, out change1, out change2); while (change1.IsAlive) { GC.Collect(2); GC.WaitForFullGCComplete(); } return change2; } private void GetChangesWithoutMiddle_Helper( SourceText original, Func<SourceText, SourceText> fnChange1, Func<SourceText, SourceText> fnChange2, out WeakReference change1, out SourceText change2) { var c1 = fnChange1(original); change1 = new WeakReference(c1); change2 = fnChange2(c1); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/CSharp/Portable/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProvider.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNamePartiallyWrittenSignatureHelpProvider", LanguageNames.CSharp), Shared] internal class GenericNamePartiallyWrittenSignatureHelpProvider : GenericNameSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenericNamePartiallyWrittenSignatureHelpProvider() { } protected override bool TryGetGenericIdentifier(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) => root.SyntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); protected override TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName(); var nextToken = lastToken.GetNextNonZeroWidthTokenOrEndOfFile(); Contract.ThrowIfTrue(nextToken.Kind() == 0); return TextSpan.FromBounds(genericIdentifier.SpanStart, nextToken.SpanStart); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNamePartiallyWrittenSignatureHelpProvider", LanguageNames.CSharp), Shared] internal class GenericNamePartiallyWrittenSignatureHelpProvider : GenericNameSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenericNamePartiallyWrittenSignatureHelpProvider() { } protected override bool TryGetGenericIdentifier(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) => root.SyntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out genericIdentifier, out lessThanToken); protected override TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { var lastToken = genericIdentifier.FindLastTokenOfPartialGenericName(); var nextToken = lastToken.GetNextNonZeroWidthTokenOrEndOfFile(); Contract.ThrowIfTrue(nextToken.Kind() == 0); return TextSpan.FromBounds(genericIdentifier.SpanStart, nextToken.SpanStart); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/Collections/OrderedSet.cs
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Collections { internal sealed class OrderedSet<T> : IEnumerable<T>, IReadOnlySet<T>, IReadOnlyList<T>, IOrderedReadOnlySet<T> { private readonly HashSet<T> _set; private readonly ArrayBuilder<T> _list; public OrderedSet() { _set = new HashSet<T>(); _list = new ArrayBuilder<T>(); } public OrderedSet(IEnumerable<T> items) : this() { AddRange(items); } public void AddRange(IEnumerable<T> items) { foreach (var item in items) { Add(item); } } public bool Add(T item) { if (_set.Add(item)) { _list.Add(item); return true; } return false; } public int Count { get { return _list.Count; } } public T this[int index] { get { return _list[index]; } } public bool Contains(T item) { return _set.Contains(item); } public ArrayBuilder<T>.Enumerator GetEnumerator() { return _list.GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_list).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } public void Clear() { _set.Clear(); _list.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; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Collections { internal sealed class OrderedSet<T> : IEnumerable<T>, IReadOnlySet<T>, IReadOnlyList<T>, IOrderedReadOnlySet<T> { private readonly HashSet<T> _set; private readonly ArrayBuilder<T> _list; public OrderedSet() { _set = new HashSet<T>(); _list = new ArrayBuilder<T>(); } public OrderedSet(IEnumerable<T> items) : this() { AddRange(items); } public void AddRange(IEnumerable<T> items) { foreach (var item in items) { Add(item); } } public bool Add(T item) { if (_set.Add(item)) { _list.Add(item); return true; } return false; } public int Count { get { return _list.Count; } } public T this[int index] { get { return _list[index]; } } public bool Contains(T item) { return _set.Contains(item); } public ArrayBuilder<T>.Enumerator GetEnumerator() { return _list.GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_list).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } public void Clear() { _set.Clear(); _list.Clear(); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// This class provides function name information for the Breakpoints window. /// </summary> internal abstract class LanguageInstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol, TParameterSymbol> : IDkmLanguageInstructionDecoder where TCompilation : Compilation where TMethodSymbol : class, IMethodSymbolInternal where TModuleSymbol : class, IModuleSymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TTypeParameterSymbol : class, ITypeParameterSymbolInternal where TParameterSymbol : class, IParameterSymbolInternal { private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder; internal LanguageInstructionDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder) { _instructionDecoder = instructionDecoder; } string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags) { try { // DkmVariableInfoFlags.FullNames was accepted by the old GetMethodName implementation, // but it was ignored. Furthermore, it's not clear what FullNames would mean with respect // to argument names in C# or Visual Basic. For consistency with the old behavior, we'll // just ignore the flag as well. Debug.Assert((argumentFlags & (DkmVariableInfoFlags.FullNames | DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags, $"Unexpected argumentFlags '{argumentFlags}'"); var instructionAddress = (DkmClrInstructionAddress)languageInstructionAddress.Address; var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance); var method = _instructionDecoder.GetMethod(compilation, instructionAddress); var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types); var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names); return _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames); } catch (NotImplementedMetadataException) { return languageInstructionAddress.GetMethodName(argumentFlags); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// This class provides function name information for the Breakpoints window. /// </summary> internal abstract class LanguageInstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol, TParameterSymbol> : IDkmLanguageInstructionDecoder where TCompilation : Compilation where TMethodSymbol : class, IMethodSymbolInternal where TModuleSymbol : class, IModuleSymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TTypeParameterSymbol : class, ITypeParameterSymbolInternal where TParameterSymbol : class, IParameterSymbolInternal { private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder; internal LanguageInstructionDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder) { _instructionDecoder = instructionDecoder; } string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags) { try { // DkmVariableInfoFlags.FullNames was accepted by the old GetMethodName implementation, // but it was ignored. Furthermore, it's not clear what FullNames would mean with respect // to argument names in C# or Visual Basic. For consistency with the old behavior, we'll // just ignore the flag as well. Debug.Assert((argumentFlags & (DkmVariableInfoFlags.FullNames | DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags, $"Unexpected argumentFlags '{argumentFlags}'"); var instructionAddress = (DkmClrInstructionAddress)languageInstructionAddress.Address; var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance); var method = _instructionDecoder.GetMethod(compilation, instructionAddress); var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types); var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names); return _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames); } catch (NotImplementedMetadataException) { return languageInstructionAddress.GetMethodName(argumentFlags); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueCapabilitiesTests.cs
// Licensed to the .NET Foundation under one or more 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 Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class EditAndContinueCapabilitiesTests { [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(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. using System; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class EditAndContinueCapabilitiesTests { [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(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 = EditAndContinueCapabilitiesParser.Parse(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,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/Symbols/CustomModifiersTuple.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { internal sealed class CustomModifiersTuple { private readonly ImmutableArray<CustomModifier> _typeCustomModifiers; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; public static readonly CustomModifiersTuple Empty = new CustomModifiersTuple(ImmutableArray<CustomModifier>.Empty, ImmutableArray<CustomModifier>.Empty); private CustomModifiersTuple(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers) { _typeCustomModifiers = typeCustomModifiers.NullToEmpty(); _refCustomModifiers = refCustomModifiers.NullToEmpty(); } public static CustomModifiersTuple Create(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers) { if (typeCustomModifiers.IsDefaultOrEmpty && refCustomModifiers.IsDefaultOrEmpty) { return Empty; } return new CustomModifiersTuple(typeCustomModifiers, refCustomModifiers); } public ImmutableArray<CustomModifier> TypeCustomModifiers { get { return _typeCustomModifiers; } } public ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { internal sealed class CustomModifiersTuple { private readonly ImmutableArray<CustomModifier> _typeCustomModifiers; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; public static readonly CustomModifiersTuple Empty = new CustomModifiersTuple(ImmutableArray<CustomModifier>.Empty, ImmutableArray<CustomModifier>.Empty); private CustomModifiersTuple(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers) { _typeCustomModifiers = typeCustomModifiers.NullToEmpty(); _refCustomModifiers = refCustomModifiers.NullToEmpty(); } public static CustomModifiersTuple Create(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers) { if (typeCustomModifiers.IsDefaultOrEmpty && refCustomModifiers.IsDefaultOrEmpty) { return Empty; } return new CustomModifiersTuple(typeCustomModifiers, refCustomModifiers); } public ImmutableArray<CustomModifier> TypeCustomModifiers { get { return _typeCustomModifiers; } } public ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/Core/Portable/Shared/Utilities/SignatureComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class SignatureComparer { public static readonly SignatureComparer Instance = new(SymbolEquivalenceComparer.Instance); public static readonly SignatureComparer IgnoreAssembliesInstance = new(SymbolEquivalenceComparer.IgnoreAssembliesInstance); private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; private SignatureComparer(SymbolEquivalenceComparer symbolEquivalenceComparer) => _symbolEquivalenceComparer = symbolEquivalenceComparer; private IEqualityComparer<IParameterSymbol> ParameterEquivalenceComparer => _symbolEquivalenceComparer.ParameterEquivalenceComparer; private IEqualityComparer<ITypeSymbol> SignatureTypeEquivalenceComparer => _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer; public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (symbol1 == null || symbol2 == null) { return false; } if (symbol1.Kind != symbol2.Kind) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive); case SymbolKind.Property: return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive); case SymbolKind.Event: return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive); } return true; } private static bool HaveSameSignature(IEventSymbol event1, IEventSymbol event2, bool caseSensitive) => IdentifiersMatch(event1.Name, event2.Name, caseSensitive); public bool HaveSameSignature(IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive) { if (!IdentifiersMatch(property1.Name, property2.Name, caseSensitive) || property1.Parameters.Length != property2.Parameters.Length || property1.IsIndexer != property2.IsIndexer) { return false; } return property1.Parameters.SequenceEqual( property2.Parameters, this.ParameterEquivalenceComparer); } private static bool BadPropertyAccessor(IMethodSymbol method1, IMethodSymbol method2) { return method1 != null && (method2 == null || method2.DeclaredAccessibility != Accessibility.Public); } public bool HaveSameSignature(IMethodSymbol method1, IMethodSymbol method2, bool caseSensitive, bool compareParameterName = false, bool isParameterCaseSensitive = false) { if ((method1.MethodKind == MethodKind.AnonymousFunction) != (method2.MethodKind == MethodKind.AnonymousFunction)) { return false; } if (method1.MethodKind != MethodKind.AnonymousFunction) { if (!IdentifiersMatch(method1.Name, method2.Name, caseSensitive)) { return false; } } if (method1.MethodKind != method2.MethodKind || method1.Arity != method2.Arity) { return false; } return HaveSameSignature(method1.Parameters, method2.Parameters, compareParameterName, isParameterCaseSensitive); } private static bool IdentifiersMatch(string identifier1, string identifier2, bool caseSensitive) { return caseSensitive ? identifier1 == identifier2 : string.Equals(identifier1, identifier2, StringComparison.OrdinalIgnoreCase); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2) { if (parameters1.Count != parameters2.Count) { return false; } return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2, bool compareParameterName, bool isCaseSensitive) { if (parameters1.Count != parameters2.Count) { return false; } for (var i = 0; i < parameters1.Count; ++i) { if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(parameters1[i], parameters2[i], compareParameterName, isCaseSensitive)) { return false; } } return true; } public bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (!HaveSameSignature(symbol1, symbol2, caseSensitive)) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: var method1 = (IMethodSymbol)symbol1; var method2 = (IMethodSymbol)symbol2; return HaveSameSignatureAndConstraintsAndReturnType(method1, method2); case SymbolKind.Property: var property1 = (IPropertySymbol)symbol1; var property2 = (IPropertySymbol)symbol2; return HaveSameReturnType(property1, property2) && HaveSameAccessors(property1, property2); case SymbolKind.Event: var ev1 = (IEventSymbol)symbol1; var ev2 = (IEventSymbol)symbol2; return HaveSameReturnType(ev1, ev2); } return true; } private static bool HaveSameAccessors(IPropertySymbol property1, IPropertySymbol property2) { if (property1.ContainingType == null || property1.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property1.GetMethod, property2.GetMethod) || BadPropertyAccessor(property1.SetMethod, property2.SetMethod)) { return false; } } if (property2.ContainingType == null || property2.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property2.GetMethod, property1.GetMethod) || BadPropertyAccessor(property2.SetMethod, property1.SetMethod)) { return false; } } return true; } private bool HaveSameSignatureAndConstraintsAndReturnType(IMethodSymbol method1, IMethodSymbol method2) { if (method1.ReturnsVoid != method2.ReturnsVoid) { return false; } if (!method1.ReturnsVoid && !this.SignatureTypeEquivalenceComparer.Equals(method1.ReturnType, method2.ReturnType)) { return false; } for (var i = 0; i < method1.TypeParameters.Length; i++) { var typeParameter1 = method1.TypeParameters[i]; var typeParameter2 = method2.TypeParameters[i]; if (!HaveSameConstraints(typeParameter1, typeParameter2)) { return false; } } return true; } private bool HaveSameConstraints(ITypeParameterSymbol typeParameter1, ITypeParameterSymbol typeParameter2) { if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint || typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint || typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint) { return false; } if (typeParameter1.ConstraintTypes.Length != typeParameter2.ConstraintTypes.Length) { return false; } return typeParameter1.ConstraintTypes.SetEquals( typeParameter2.ConstraintTypes, this.SignatureTypeEquivalenceComparer); } private bool HaveSameReturnType(IPropertySymbol property1, IPropertySymbol property2) => this.SignatureTypeEquivalenceComparer.Equals(property1.Type, property2.Type); private bool HaveSameReturnType(IEventSymbol ev1, IEventSymbol ev2) => this.SignatureTypeEquivalenceComparer.Equals(ev1.Type, ev2.Type); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class SignatureComparer { public static readonly SignatureComparer Instance = new(SymbolEquivalenceComparer.Instance); public static readonly SignatureComparer IgnoreAssembliesInstance = new(SymbolEquivalenceComparer.IgnoreAssembliesInstance); private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; private SignatureComparer(SymbolEquivalenceComparer symbolEquivalenceComparer) => _symbolEquivalenceComparer = symbolEquivalenceComparer; private IEqualityComparer<IParameterSymbol> ParameterEquivalenceComparer => _symbolEquivalenceComparer.ParameterEquivalenceComparer; private IEqualityComparer<ITypeSymbol> SignatureTypeEquivalenceComparer => _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer; public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (symbol1 == null || symbol2 == null) { return false; } if (symbol1.Kind != symbol2.Kind) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive); case SymbolKind.Property: return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive); case SymbolKind.Event: return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive); } return true; } private static bool HaveSameSignature(IEventSymbol event1, IEventSymbol event2, bool caseSensitive) => IdentifiersMatch(event1.Name, event2.Name, caseSensitive); public bool HaveSameSignature(IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive) { if (!IdentifiersMatch(property1.Name, property2.Name, caseSensitive) || property1.Parameters.Length != property2.Parameters.Length || property1.IsIndexer != property2.IsIndexer) { return false; } return property1.Parameters.SequenceEqual( property2.Parameters, this.ParameterEquivalenceComparer); } private static bool BadPropertyAccessor(IMethodSymbol method1, IMethodSymbol method2) { return method1 != null && (method2 == null || method2.DeclaredAccessibility != Accessibility.Public); } public bool HaveSameSignature(IMethodSymbol method1, IMethodSymbol method2, bool caseSensitive, bool compareParameterName = false, bool isParameterCaseSensitive = false) { if ((method1.MethodKind == MethodKind.AnonymousFunction) != (method2.MethodKind == MethodKind.AnonymousFunction)) { return false; } if (method1.MethodKind != MethodKind.AnonymousFunction) { if (!IdentifiersMatch(method1.Name, method2.Name, caseSensitive)) { return false; } } if (method1.MethodKind != method2.MethodKind || method1.Arity != method2.Arity) { return false; } return HaveSameSignature(method1.Parameters, method2.Parameters, compareParameterName, isParameterCaseSensitive); } private static bool IdentifiersMatch(string identifier1, string identifier2, bool caseSensitive) { return caseSensitive ? identifier1 == identifier2 : string.Equals(identifier1, identifier2, StringComparison.OrdinalIgnoreCase); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2) { if (parameters1.Count != parameters2.Count) { return false; } return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2, bool compareParameterName, bool isCaseSensitive) { if (parameters1.Count != parameters2.Count) { return false; } for (var i = 0; i < parameters1.Count; ++i) { if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(parameters1[i], parameters2[i], compareParameterName, isCaseSensitive)) { return false; } } return true; } public bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (!HaveSameSignature(symbol1, symbol2, caseSensitive)) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: var method1 = (IMethodSymbol)symbol1; var method2 = (IMethodSymbol)symbol2; return HaveSameSignatureAndConstraintsAndReturnType(method1, method2); case SymbolKind.Property: var property1 = (IPropertySymbol)symbol1; var property2 = (IPropertySymbol)symbol2; return HaveSameReturnType(property1, property2) && HaveSameAccessors(property1, property2); case SymbolKind.Event: var ev1 = (IEventSymbol)symbol1; var ev2 = (IEventSymbol)symbol2; return HaveSameReturnType(ev1, ev2); } return true; } private static bool HaveSameAccessors(IPropertySymbol property1, IPropertySymbol property2) { if (property1.ContainingType == null || property1.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property1.GetMethod, property2.GetMethod) || BadPropertyAccessor(property1.SetMethod, property2.SetMethod)) { return false; } } if (property2.ContainingType == null || property2.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property2.GetMethod, property1.GetMethod) || BadPropertyAccessor(property2.SetMethod, property1.SetMethod)) { return false; } } return true; } private bool HaveSameSignatureAndConstraintsAndReturnType(IMethodSymbol method1, IMethodSymbol method2) { if (method1.ReturnsVoid != method2.ReturnsVoid) { return false; } if (!method1.ReturnsVoid && !this.SignatureTypeEquivalenceComparer.Equals(method1.ReturnType, method2.ReturnType)) { return false; } for (var i = 0; i < method1.TypeParameters.Length; i++) { var typeParameter1 = method1.TypeParameters[i]; var typeParameter2 = method2.TypeParameters[i]; if (!HaveSameConstraints(typeParameter1, typeParameter2)) { return false; } } return true; } private bool HaveSameConstraints(ITypeParameterSymbol typeParameter1, ITypeParameterSymbol typeParameter2) { if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint || typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint || typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint) { return false; } if (typeParameter1.ConstraintTypes.Length != typeParameter2.ConstraintTypes.Length) { return false; } return typeParameter1.ConstraintTypes.SetEquals( typeParameter2.ConstraintTypes, this.SignatureTypeEquivalenceComparer); } private bool HaveSameReturnType(IPropertySymbol property1, IPropertySymbol property2) => this.SignatureTypeEquivalenceComparer.Equals(property1.Type, property2.Type); private bool HaveSameReturnType(IEventSymbol ev1, IEventSymbol ev2) => this.SignatureTypeEquivalenceComparer.Equals(ev1.Type, ev2.Type); } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Compilers/Core/Portable/Diagnostic/CommonMessageProvider.cs
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Abstracts the ability to classify and load messages for error codes. Allows the error /// infrastructure to be reused between C# and VB. /// </summary> internal abstract class CommonMessageProvider { /// <summary> /// Caches the return values for <see cref="GetIdForErrorCode(int)"/>. /// </summary> private static readonly ConcurrentDictionary<(string prefix, int code), string> s_errorIdCache = new ConcurrentDictionary<(string prefix, int code), string>(); /// <summary> /// Given an error code, get the severity (warning or error) of the code. /// </summary> public abstract DiagnosticSeverity GetSeverity(int code); /// <summary> /// Load the message for the given error code. If the message contains /// "fill-in" placeholders, those should be expressed in standard string.Format notation /// and be in the string. /// </summary> public abstract string LoadMessage(int code, CultureInfo? language); /// <summary> /// Get an optional localizable title for the given diagnostic code. /// </summary> public abstract LocalizableString GetTitle(int code); /// <summary> /// Get an optional localizable description for the given diagnostic code. /// </summary> public abstract LocalizableString GetDescription(int code); /// <summary> /// Get a localizable message format string for the given diagnostic code. /// </summary> public abstract LocalizableString GetMessageFormat(int code); /// <summary> /// Get an optional help link for the given diagnostic code. /// </summary> public abstract string GetHelpLink(int code); /// <summary> /// Get the diagnostic category for the given diagnostic code. /// Default category is <see cref="Diagnostic.CompilerDiagnosticCategory"/>. /// </summary> public abstract string GetCategory(int code); /// <summary> /// Get the text prefix (e.g., "CS" for C#) used on error messages. /// </summary> public abstract string CodePrefix { get; } /// <summary> /// Get the warning level for warnings (e.g., 1 or greater for C#). VB does not have warning /// levels and always uses 1. Errors should return 0. /// </summary> public abstract int GetWarningLevel(int code); /// <summary> /// Type that defines error codes. For testing purposes only. /// </summary> public abstract Type ErrorCodeType { get; } /// <summary> /// Create a simple language specific diagnostic for given error code. /// </summary> public Diagnostic CreateDiagnostic(int code, Location location) { return CreateDiagnostic(code, location, Array.Empty<object>()); } /// <summary> /// Create a simple language specific diagnostic with no location for given info. /// </summary> public abstract Diagnostic CreateDiagnostic(DiagnosticInfo info); /// <summary> /// Create a simple language specific diagnostic for given error code. /// </summary> public abstract Diagnostic CreateDiagnostic(int code, Location location, params object[] args); /// <summary> /// Given a message identifier (e.g., CS0219), severity, warning as error and a culture, /// get the entire prefix (e.g., "error CS0219: Warning as Error:" for C# or "error BC42024:" for VB) used on error messages. /// </summary> public abstract string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo? culture); /// <summary> /// Convert given symbol to string representation. /// </summary> public abstract string GetErrorDisplayString(ISymbol symbol); /// <summary> /// Given an error code (like 1234) return the identifier (CS1234 or BC1234). /// </summary> [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/31964", AllowCaptures = false, Constraint = "Frequently called by error list filtering; avoid allocations")] public string GetIdForErrorCode(int errorCode) { return s_errorIdCache.GetOrAdd((CodePrefix, errorCode), key => key.prefix + key.code.ToString("0000")); } /// <summary> /// Produces the filtering action for the diagnostic based on the options passed in. /// </summary> /// <returns> /// A new <see cref="DiagnosticInfo"/> with new effective severity based on the options or null if the /// diagnostic has been suppressed. /// </returns> public abstract ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options); /// <summary> /// Filter a <see cref="DiagnosticInfo"/> based on the compilation options so that /nowarn and /warnaserror etc. take effect.options /// </summary> /// <returns>A <see cref="DiagnosticInfo"/> with effective severity based on option or null if suppressed.</returns> public DiagnosticInfo? FilterDiagnosticInfo(DiagnosticInfo diagnosticInfo, CompilationOptions options) { var report = this.GetDiagnosticReport(diagnosticInfo, options); switch (report) { case ReportDiagnostic.Error: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Error); case ReportDiagnostic.Warn: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Warning); case ReportDiagnostic.Info: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Info); case ReportDiagnostic.Hidden: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Hidden); case ReportDiagnostic.Suppress: return null; default: return diagnosticInfo; } } // Common error messages public abstract int ERR_FailedToCreateTempFile { get; } public abstract int ERR_MultipleAnalyzerConfigsInSameDir { get; } // command line: public abstract int ERR_ExpectedSingleScript { get; } public abstract int ERR_OpenResponseFile { get; } public abstract int ERR_InvalidPathMap { get; } public abstract int FTL_InvalidInputFileName { get; } public abstract int ERR_FileNotFound { get; } public abstract int ERR_NoSourceFile { get; } public abstract int ERR_CantOpenFileWrite { get; } public abstract int ERR_OutputWriteFailed { get; } public abstract int WRN_NoConfigNotOnCommandLine { get; } public abstract int ERR_BinaryFile { get; } public abstract int WRN_UnableToLoadAnalyzer { get; } public abstract int INF_UnableToLoadSomeTypesInAnalyzer { get; } public abstract int WRN_AnalyzerCannotBeCreated { get; } public abstract int WRN_NoAnalyzerInAssembly { get; } public abstract int WRN_AnalyzerReferencesFramework { get; } public abstract int ERR_CantReadRulesetFile { get; } public abstract int ERR_CompileCancelled { get; } // parse options: public abstract int ERR_BadSourceCodeKind { get; } public abstract int ERR_BadDocumentationMode { get; } // compilation options: public abstract int ERR_BadCompilationOptionValue { get; } public abstract int ERR_MutuallyExclusiveOptions { get; } // emit options: public abstract int ERR_InvalidDebugInformationFormat { get; } public abstract int ERR_InvalidFileAlignment { get; } public abstract int ERR_InvalidSubsystemVersion { get; } public abstract int ERR_InvalidOutputName { get; } public abstract int ERR_InvalidInstrumentationKind { get; } public abstract int ERR_InvalidHashAlgorithmName { get; } // reference manager: public abstract int ERR_MetadataFileNotAssembly { get; } public abstract int ERR_MetadataFileNotModule { get; } public abstract int ERR_InvalidAssemblyMetadata { get; } public abstract int ERR_InvalidModuleMetadata { get; } public abstract int ERR_ErrorOpeningAssemblyFile { get; } public abstract int ERR_ErrorOpeningModuleFile { get; } public abstract int ERR_MetadataFileNotFound { get; } public abstract int ERR_MetadataReferencesNotSupported { get; } public abstract int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage { get; } public abstract void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); public abstract void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); // signing: public abstract int ERR_PublicKeyFileFailure { get; } public abstract int ERR_PublicKeyContainerFailure { get; } public abstract int ERR_OptionMustBeAbsolutePath { get; } // resources: public abstract int ERR_CantReadResource { get; } public abstract int ERR_CantOpenWin32Resource { get; } public abstract int ERR_CantOpenWin32Manifest { get; } public abstract int ERR_CantOpenWin32Icon { get; } public abstract int ERR_BadWin32Resource { get; } public abstract int ERR_ErrorBuildingWin32Resource { get; } public abstract int ERR_ResourceNotUnique { get; } public abstract int ERR_ResourceFileNameNotUnique { get; } public abstract int ERR_ResourceInModule { get; } // pseudo-custom attributes: public abstract int ERR_PermissionSetAttributeFileReadError { get; } // PDB writing: public abstract int ERR_EncodinglessSyntaxTree { get; } public abstract int WRN_PdbUsingNameTooLong { get; } public abstract int WRN_PdbLocalNameTooLong { get; } public abstract int ERR_PdbWritingFailed { get; } // PE writing: public abstract int ERR_MetadataNameTooLong { get; } public abstract int ERR_EncReferenceToAddedMember { get; } public abstract int ERR_TooManyUserStrings { get; } public abstract int ERR_PeWritingFailure { get; } public abstract int ERR_ModuleEmitFailure { get; } public abstract int ERR_EncUpdateFailedMissingAttribute { get; } public abstract int ERR_InvalidDebugInfo { get; } // Generators: public abstract int WRN_GeneratorFailedDuringInitialization { get; } public abstract int WRN_GeneratorFailedDuringGeneration { get; } /// <summary> /// Takes an exception produced while writing to a file stream and produces a diagnostic. /// </summary> public void ReportStreamWriteException(Exception e, string filePath, DiagnosticBag diagnostics) { diagnostics.Add(CreateDiagnostic(ERR_OutputWriteFailed, Location.None, filePath, e.Message)); } protected abstract void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute); public void ReportInvalidAttributeArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportInvalidAttributeArgument(diagnosticBag, attributeSyntax, parameterIndex, attribute); } } protected abstract void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName); public void ReportInvalidNamedArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportInvalidNamedArgument(diagnosticBag, attributeSyntax, namedArgumentIndex, attributeClass, parameterName); } } protected abstract void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex); public void ReportParameterNotValidForType(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportParameterNotValidForType(diagnosticBag, attributeSyntax, namedArgumentIndex); } } protected abstract void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); public void ReportMarshalUnmanagedTypeNotValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportMarshalUnmanagedTypeNotValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); } } protected abstract void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); public void ReportMarshalUnmanagedTypeOnlyValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportMarshalUnmanagedTypeOnlyValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); } } protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName); public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName); } } protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2); public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName1, parameterName2); } } public abstract int ERR_BadAssemblyName { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Abstracts the ability to classify and load messages for error codes. Allows the error /// infrastructure to be reused between C# and VB. /// </summary> internal abstract class CommonMessageProvider { /// <summary> /// Caches the return values for <see cref="GetIdForErrorCode(int)"/>. /// </summary> private static readonly ConcurrentDictionary<(string prefix, int code), string> s_errorIdCache = new ConcurrentDictionary<(string prefix, int code), string>(); /// <summary> /// Given an error code, get the severity (warning or error) of the code. /// </summary> public abstract DiagnosticSeverity GetSeverity(int code); /// <summary> /// Load the message for the given error code. If the message contains /// "fill-in" placeholders, those should be expressed in standard string.Format notation /// and be in the string. /// </summary> public abstract string LoadMessage(int code, CultureInfo? language); /// <summary> /// Get an optional localizable title for the given diagnostic code. /// </summary> public abstract LocalizableString GetTitle(int code); /// <summary> /// Get an optional localizable description for the given diagnostic code. /// </summary> public abstract LocalizableString GetDescription(int code); /// <summary> /// Get a localizable message format string for the given diagnostic code. /// </summary> public abstract LocalizableString GetMessageFormat(int code); /// <summary> /// Get an optional help link for the given diagnostic code. /// </summary> public abstract string GetHelpLink(int code); /// <summary> /// Get the diagnostic category for the given diagnostic code. /// Default category is <see cref="Diagnostic.CompilerDiagnosticCategory"/>. /// </summary> public abstract string GetCategory(int code); /// <summary> /// Get the text prefix (e.g., "CS" for C#) used on error messages. /// </summary> public abstract string CodePrefix { get; } /// <summary> /// Get the warning level for warnings (e.g., 1 or greater for C#). VB does not have warning /// levels and always uses 1. Errors should return 0. /// </summary> public abstract int GetWarningLevel(int code); /// <summary> /// Type that defines error codes. For testing purposes only. /// </summary> public abstract Type ErrorCodeType { get; } /// <summary> /// Create a simple language specific diagnostic for given error code. /// </summary> public Diagnostic CreateDiagnostic(int code, Location location) { return CreateDiagnostic(code, location, Array.Empty<object>()); } /// <summary> /// Create a simple language specific diagnostic with no location for given info. /// </summary> public abstract Diagnostic CreateDiagnostic(DiagnosticInfo info); /// <summary> /// Create a simple language specific diagnostic for given error code. /// </summary> public abstract Diagnostic CreateDiagnostic(int code, Location location, params object[] args); /// <summary> /// Given a message identifier (e.g., CS0219), severity, warning as error and a culture, /// get the entire prefix (e.g., "error CS0219: Warning as Error:" for C# or "error BC42024:" for VB) used on error messages. /// </summary> public abstract string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo? culture); /// <summary> /// Convert given symbol to string representation. /// </summary> public abstract string GetErrorDisplayString(ISymbol symbol); /// <summary> /// Given an error code (like 1234) return the identifier (CS1234 or BC1234). /// </summary> [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/31964", AllowCaptures = false, Constraint = "Frequently called by error list filtering; avoid allocations")] public string GetIdForErrorCode(int errorCode) { return s_errorIdCache.GetOrAdd((CodePrefix, errorCode), key => key.prefix + key.code.ToString("0000")); } /// <summary> /// Produces the filtering action for the diagnostic based on the options passed in. /// </summary> /// <returns> /// A new <see cref="DiagnosticInfo"/> with new effective severity based on the options or null if the /// diagnostic has been suppressed. /// </returns> public abstract ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options); /// <summary> /// Filter a <see cref="DiagnosticInfo"/> based on the compilation options so that /nowarn and /warnaserror etc. take effect.options /// </summary> /// <returns>A <see cref="DiagnosticInfo"/> with effective severity based on option or null if suppressed.</returns> public DiagnosticInfo? FilterDiagnosticInfo(DiagnosticInfo diagnosticInfo, CompilationOptions options) { var report = this.GetDiagnosticReport(diagnosticInfo, options); switch (report) { case ReportDiagnostic.Error: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Error); case ReportDiagnostic.Warn: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Warning); case ReportDiagnostic.Info: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Info); case ReportDiagnostic.Hidden: return diagnosticInfo.GetInstanceWithSeverity(DiagnosticSeverity.Hidden); case ReportDiagnostic.Suppress: return null; default: return diagnosticInfo; } } // Common error messages public abstract int ERR_FailedToCreateTempFile { get; } public abstract int ERR_MultipleAnalyzerConfigsInSameDir { get; } // command line: public abstract int ERR_ExpectedSingleScript { get; } public abstract int ERR_OpenResponseFile { get; } public abstract int ERR_InvalidPathMap { get; } public abstract int FTL_InvalidInputFileName { get; } public abstract int ERR_FileNotFound { get; } public abstract int ERR_NoSourceFile { get; } public abstract int ERR_CantOpenFileWrite { get; } public abstract int ERR_OutputWriteFailed { get; } public abstract int WRN_NoConfigNotOnCommandLine { get; } public abstract int ERR_BinaryFile { get; } public abstract int WRN_UnableToLoadAnalyzer { get; } public abstract int INF_UnableToLoadSomeTypesInAnalyzer { get; } public abstract int WRN_AnalyzerCannotBeCreated { get; } public abstract int WRN_NoAnalyzerInAssembly { get; } public abstract int WRN_AnalyzerReferencesFramework { get; } public abstract int ERR_CantReadRulesetFile { get; } public abstract int ERR_CompileCancelled { get; } // parse options: public abstract int ERR_BadSourceCodeKind { get; } public abstract int ERR_BadDocumentationMode { get; } // compilation options: public abstract int ERR_BadCompilationOptionValue { get; } public abstract int ERR_MutuallyExclusiveOptions { get; } // emit options: public abstract int ERR_InvalidDebugInformationFormat { get; } public abstract int ERR_InvalidFileAlignment { get; } public abstract int ERR_InvalidSubsystemVersion { get; } public abstract int ERR_InvalidOutputName { get; } public abstract int ERR_InvalidInstrumentationKind { get; } public abstract int ERR_InvalidHashAlgorithmName { get; } // reference manager: public abstract int ERR_MetadataFileNotAssembly { get; } public abstract int ERR_MetadataFileNotModule { get; } public abstract int ERR_InvalidAssemblyMetadata { get; } public abstract int ERR_InvalidModuleMetadata { get; } public abstract int ERR_ErrorOpeningAssemblyFile { get; } public abstract int ERR_ErrorOpeningModuleFile { get; } public abstract int ERR_MetadataFileNotFound { get; } public abstract int ERR_MetadataReferencesNotSupported { get; } public abstract int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage { get; } public abstract void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); public abstract void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity); // signing: public abstract int ERR_PublicKeyFileFailure { get; } public abstract int ERR_PublicKeyContainerFailure { get; } public abstract int ERR_OptionMustBeAbsolutePath { get; } // resources: public abstract int ERR_CantReadResource { get; } public abstract int ERR_CantOpenWin32Resource { get; } public abstract int ERR_CantOpenWin32Manifest { get; } public abstract int ERR_CantOpenWin32Icon { get; } public abstract int ERR_BadWin32Resource { get; } public abstract int ERR_ErrorBuildingWin32Resource { get; } public abstract int ERR_ResourceNotUnique { get; } public abstract int ERR_ResourceFileNameNotUnique { get; } public abstract int ERR_ResourceInModule { get; } // pseudo-custom attributes: public abstract int ERR_PermissionSetAttributeFileReadError { get; } // PDB writing: public abstract int ERR_EncodinglessSyntaxTree { get; } public abstract int WRN_PdbUsingNameTooLong { get; } public abstract int WRN_PdbLocalNameTooLong { get; } public abstract int ERR_PdbWritingFailed { get; } // PE writing: public abstract int ERR_MetadataNameTooLong { get; } public abstract int ERR_EncReferenceToAddedMember { get; } public abstract int ERR_TooManyUserStrings { get; } public abstract int ERR_PeWritingFailure { get; } public abstract int ERR_ModuleEmitFailure { get; } public abstract int ERR_EncUpdateFailedMissingAttribute { get; } public abstract int ERR_InvalidDebugInfo { get; } // Generators: public abstract int WRN_GeneratorFailedDuringInitialization { get; } public abstract int WRN_GeneratorFailedDuringGeneration { get; } /// <summary> /// Takes an exception produced while writing to a file stream and produces a diagnostic. /// </summary> public void ReportStreamWriteException(Exception e, string filePath, DiagnosticBag diagnostics) { diagnostics.Add(CreateDiagnostic(ERR_OutputWriteFailed, Location.None, filePath, e.Message)); } protected abstract void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute); public void ReportInvalidAttributeArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportInvalidAttributeArgument(diagnosticBag, attributeSyntax, parameterIndex, attribute); } } protected abstract void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName); public void ReportInvalidNamedArgument(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportInvalidNamedArgument(diagnosticBag, attributeSyntax, namedArgumentIndex, attributeClass, parameterName); } } protected abstract void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex); public void ReportParameterNotValidForType(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportParameterNotValidForType(diagnosticBag, attributeSyntax, namedArgumentIndex); } } protected abstract void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); public void ReportMarshalUnmanagedTypeNotValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportMarshalUnmanagedTypeNotValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); } } protected abstract void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute); public void ReportMarshalUnmanagedTypeOnlyValidForFields(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportMarshalUnmanagedTypeOnlyValidForFields(diagnosticBag, attributeSyntax, parameterIndex, unmanagedTypeName, attribute); } } protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName); public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName); } } protected abstract void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2); public void ReportAttributeParameterRequired(BindingDiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { ReportAttributeParameterRequired(diagnosticBag, attributeSyntax, parameterName1, parameterName2); } } public abstract int ERR_BadAssemblyName { get; } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.AddBraces { public partial class AddBracesTests { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument1() { var input = @" class Program1 { static void Main() { {|FixAllInDocument:if|} (true) if (true) return; } } "; var expected = @" class Program1 { static void Main() { if (true) { if (true) { return; } } } } "; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument2() { var input = @" class Program1 { static void Main() { if (true) {|FixAllInDocument:if|} (true) return; } } "; var expected = @" class Program1 { static void Main() { if (true) { if (true) { return; } } } } "; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInDocument:if|} (true) return; if (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInProject:if|} (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) { return; } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInSolution:if|} (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) { return; } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) { return; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.AddBraces { public partial class AddBracesTests { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument1() { var input = @" class Program1 { static void Main() { {|FixAllInDocument:if|} (true) if (true) return; } } "; var expected = @" class Program1 { static void Main() { if (true) { if (true) { return; } } } } "; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument2() { var input = @" class Program1 { static void Main() { if (true) {|FixAllInDocument:if|} (true) return; } } "; var expected = @" class Program1 { static void Main() { if (true) { if (true) { return; } } } } "; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInDocument:if|} (true) return; if (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInProject:if|} (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) { return; } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { {|FixAllInSolution:if|} (true) return; } } </Document> <Document> class Program2 { static void Main() { if (true) return; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) return; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> class Program1 { static void Main() { if (true) { return; } } } </Document> <Document> class Program2 { static void Main() { if (true) { return; } } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Program3 { static void Main() { if (true) { return; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/OperatorKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public OperatorKeywordRecommender() : base(SyntaxKind.OperatorKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // cases: // public static implicit | // public static explicit | var token = context.TargetToken; return token.Kind() == SyntaxKind.ImplicitKeyword || token.Kind() == SyntaxKind.ExplicitKeyword; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public OperatorKeywordRecommender() : base(SyntaxKind.OperatorKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // cases: // public static implicit | // public static explicit | var token = context.TargetToken; return token.Kind() == SyntaxKind.ImplicitKeyword || token.Kind() == SyntaxKind.ExplicitKeyword; } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/CSharpTest/Structure/CompilationUnitStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 CompilationUnitStructureTests : AbstractCSharpSyntaxNodeStructureTests<CompilationUnitSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new CompilationUnitStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsings() { const string code = @" $${|hint:using {|textspan:System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsingAliases() { const string code = @" $${|hint:using {|textspan:System; using System.Core; using text = System.Text; using linq = System.Linq;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliases() { const string code = @" $${|hint:extern {|textspan:alias Goo; extern alias Bar;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesAndUsings() { const string code = @" $${|hint:extern {|textspan:alias Goo; extern alias Bar; using System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; extern alias Bar; // Goo // Bar using System; using System.Core;|}|} {|span3:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span3", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsingsWithComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:using {|textspan2:System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesWithComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; extern alias Bar;|}|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestWithComments() { const string code = @" $${|span1:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestWithCommentsAtEnd() { const string code = @" $${|hint1:using {|textspan1:System;|}|} {|span2:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span2", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(539359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539359")] public async Task TestUsingKeywordWithSpace() { const string code = @" $${|hint:using|} {|textspan:|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(16186, "https://github.com/dotnet/roslyn/issues/16186")] public async Task TestInvalidComment() { const string code = @"$${|span:/*/|}"; await VerifyBlockSpansAsync(code, Region("span", "/* / ...", 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class CompilationUnitStructureTests : AbstractCSharpSyntaxNodeStructureTests<CompilationUnitSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new CompilationUnitStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsings() { const string code = @" $${|hint:using {|textspan:System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsingAliases() { const string code = @" $${|hint:using {|textspan:System; using System.Core; using text = System.Text; using linq = System.Linq;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliases() { const string code = @" $${|hint:extern {|textspan:alias Goo; extern alias Bar;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesAndUsings() { const string code = @" $${|hint:extern {|textspan:alias Goo; extern alias Bar; using System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesAndUsingsWithLeadingTrailingAndNestedComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; extern alias Bar; // Goo // Bar using System; using System.Core;|}|} {|span3:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span3", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestUsingsWithComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:using {|textspan2:System; using System.Core;|}|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestExternAliasesWithComments() { const string code = @" $${|span1:// Goo // Bar|} {|hint2:extern {|textspan2:alias Goo; extern alias Bar;|}|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestWithComments() { const string code = @" $${|span1:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("span1", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestWithCommentsAtEnd() { const string code = @" $${|hint1:using {|textspan1:System;|}|} {|span2:// Goo // Bar|}"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true), Region("span2", "// Goo ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(539359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539359")] public async Task TestUsingKeywordWithSpace() { const string code = @" $${|hint:using|} {|textspan:|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(16186, "https://github.com/dotnet/roslyn/issues/16186")] public async Task TestInvalidComment() { const string code = @"$${|span:/*/|}"; await VerifyBlockSpansAsync(code, Region("span", "/* / ...", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)> Public NotInheritable Class IntroduceUsingStatementTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider End Function <Theory> <InlineData("D[||]im name = disposable")> <InlineData("Dim[||] name = disposable")> <InlineData("Dim [||]name = disposable")> <InlineData("Dim na[||]me = disposable")> <InlineData("Dim name[||] = disposable")> <InlineData("Dim name [||]= disposable")> <InlineData("Dim name =[||] disposable")> <InlineData("Dim name = [||]disposable")> <InlineData("[|Dim name = disposable|]")> <InlineData("Dim name = disposable[||]")> <InlineData("Dim name = disposable[||]")> Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForVerticalSelection() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) [| " & " Dim name = disposable |] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||]Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||] Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable[||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable [||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Theory> <InlineData("Dim name = d[||]isposable")> <InlineData("Dim name = disposabl[||]e")> <InlineData("Dim name=[|disposable|]")> Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name As System.IDisposable =[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Using [||]name = disposable End Using End Sub End Class") End Function <Theory> <InlineData("[||]Dim x = disposable, y = disposable")> <InlineData("Dim [||]x = disposable, y = disposable")> <InlineData("Dim x = disposable, [||]y = disposable")> <InlineData("Dim x = disposable, y = disposable[||]")> Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable) Sub M(disposable As T) Dim x = disposable[||] End Sub End Class", "Class C(Of T As System.IDisposable) Sub M(disposable As T) Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task Await TestMissingAsync("Class C(Of T) Sub M(disposable as T) Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) ' Comment Dim x = disposable[||] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) ' Comment Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' Comment End Using End Sub End Class") End Function <Fact> Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable End Using ' Comment End Sub End Class") End Function <Fact> Public Async Function ValidPreprocessorStaysValid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable End Using #End If End Sub End Class") End Function <Fact> Public Async Function InvalidPreprocessorStaysInvalid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If Dim discard = x End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable #End If Dim discard = x End Using End Sub End Class") End Function <Fact> Public Async Function StatementsAreSurroundedByMinimalScope() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) M(null) Dim x = disposable[||] M(null) M(x) M(null) End Sub End Class", "Class C Sub M(disposable As System.IDisposable) M(null) Using x = disposable M(null) M(x) End Using M(null) End Sub End Class") End Function <Fact> Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' A M(x) ' B ' C End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' A M(x) ' B End Using ' C End Sub End Class") End Function <Fact> Public Async Function WorksInSelectCases() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Dim x = disposable[||] M(x) End Select End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Using x = disposable M(x) End Using End Select End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Else Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) New Action(Function() Dim x = disposable[||]) End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() buffer.Clone() Dim a = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() buffer.Clone() End Using Dim a = 1 End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b Dim d = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b End Using Dim d = 1 End Sub End Class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)> Public NotInheritable Class IntroduceUsingStatementTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider End Function <Theory> <InlineData("D[||]im name = disposable")> <InlineData("Dim[||] name = disposable")> <InlineData("Dim [||]name = disposable")> <InlineData("Dim na[||]me = disposable")> <InlineData("Dim name[||] = disposable")> <InlineData("Dim name [||]= disposable")> <InlineData("Dim name =[||] disposable")> <InlineData("Dim name = [||]disposable")> <InlineData("[|Dim name = disposable|]")> <InlineData("Dim name = disposable[||]")> <InlineData("Dim name = disposable[||]")> Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForVerticalSelection() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) [| " & " Dim name = disposable |] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||]Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable [||] Dim name = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Dim ignore = disposable Using name = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable[||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name = disposable [||] Dim ignore = disposable End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using name = disposable End Using Dim ignore = disposable End Sub End Class") End Function <Theory> <InlineData("Dim name = d[||]isposable")> <InlineData("Dim name = disposabl[||]e")> <InlineData("Dim name=[|disposable|]")> Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim name As System.IDisposable =[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Using [||]name = disposable End Using End Sub End Class") End Function <Theory> <InlineData("[||]Dim x = disposable, y = disposable")> <InlineData("Dim [||]x = disposable, y = disposable")> <InlineData("Dim x = disposable, [||]y = disposable")> <InlineData("Dim x = disposable, y = disposable[||]")> Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) " & declaration & " End Sub End Class") End Function <Fact> Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable) Sub M(disposable As T) Dim x = disposable[||] End Sub End Class", "Class C(Of T As System.IDisposable) Sub M(disposable As T) Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task Await TestMissingAsync("Class C(Of T) Sub M(disposable as T) Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) ' Comment Dim x = disposable[||] End Sub End Class", "Class C Sub M(disposable As System.IDisposable) ' Comment Using x = disposable End Using End Sub End Class") End Function <Fact> Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' Comment End Using End Sub End Class") End Function <Fact> Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' Comment End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable End Using ' Comment End Sub End Class") End Function <Fact> Public Async Function ValidPreprocessorStaysValid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable End Using #End If End Sub End Class") End Function <Fact> Public Async Function InvalidPreprocessorStaysInvalid() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) #If True Then Dim x = disposable[||] #End If Dim discard = x End Sub End Class", "Class C Sub M(disposable As System.IDisposable) #If True Then Using x = disposable #End If Dim discard = x End Using End Sub End Class") End Function <Fact> Public Async Function StatementsAreSurroundedByMinimalScope() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) M(null) Dim x = disposable[||] M(null) M(x) M(null) End Sub End Class", "Class C Sub M(disposable As System.IDisposable) M(null) Using x = disposable M(null) M(x) End Using M(null) End Sub End Class") End Function <Fact> Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Dim x = disposable[||] ' A M(x) ' B ' C End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Using x = disposable ' A M(x) ' B End Using ' C End Sub End Class") End Function <Fact> Public Async Function WorksInSelectCases() As Task Await TestInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Dim x = disposable[||] M(x) End Select End Sub End Class", "Class C Sub M(disposable As System.IDisposable) Select Case disposable Case Else Using x = disposable M(x) End Using End Select End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) If disposable IsNot Nothing Then Else Dim x = disposable[||] End Sub End Class") End Function <Fact> Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task Await TestMissingInRegularAndScriptAsync("Class C Sub M(disposable As System.IDisposable) New Action(Function() Dim x = disposable[||]) End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() buffer.Clone() Dim a = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() buffer.Clone() End Using Dim a = 1 End Sub End Class") End Function <Fact> <WorkItem(35237, "https://github.com/dotnet/roslyn/issues/35237")> Public Async Function ExpandsToIncludeSurroundedMultiVariableDeclarations() As Task Await TestInRegularAndScriptAsync( "Imports System.IO Class C Sub M() Dim reader = New MemoryStream()[||] Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b Dim d = 1 End Sub End Class", "Imports System.IO Class C Sub M() Using reader = New MemoryStream() Dim buffer = reader.GetBuffer() Dim a As Integer = buffer(0), b As Integer = a Dim c = b End Using Dim d = 1 End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.de.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="de" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn-Diagnose</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn-Diagnose</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="de" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn-Diagnose</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn-Diagnose</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/Core/Portable/Indentation/DefaultInferredIndentationService.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Indentation { [ExportWorkspaceService(typeof(IInferredIndentationService), ServiceLayer.Default), Shared] internal sealed class DefaultInferredIndentationService : IInferredIndentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultInferredIndentationService() { } public Task<DocumentOptionSet> GetDocumentOptionsWithInferredIndentationAsync(Document document, bool explicitFormat, CancellationToken cancellationToken) { // The workspaces layer doesn't have any smarts to infer spaces/tabs settings without an editorconfig, so just return // the document's options. return document.GetOptionsAsync(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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Indentation { [ExportWorkspaceService(typeof(IInferredIndentationService), ServiceLayer.Default), Shared] internal sealed class DefaultInferredIndentationService : IInferredIndentationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultInferredIndentationService() { } public Task<DocumentOptionSet> GetDocumentOptionsWithInferredIndentationAsync(Document document, bool explicitFormat, CancellationToken cancellationToken) { // The workspaces layer doesn't have any smarts to infer spaces/tabs settings without an editorconfig, so just return // the document's options. return document.GetOptionsAsync(cancellationToken); } } }
-1